简体   繁体   English

字符串比较C-strcmp()

[英]String comparison C - strcmp()

I'm trying to compare two strings, but I fail achieving that. 我正在尝试比较两个字符串,但未能实现。 Why? 为什么?

#include <stdio.h>
#include <string.h>

int main(){
    float a = 1231.23123;
    char b[32];
    sprintf(b, "%f", a);
    printf("%s\n", b);
    char c[32] = "1231.23123";
    if (strcmp(c, b) == 0){
        printf("SUCCES\n");
    }
    else{
        printf("DIFFER\n");
    }
    return 0;
}

Result: 结果:

1231.231201
DIFFER

The two strings are clearly different, so strcmp() is working as it should. 这两个字符串明显不同,因此strcmp()可以正常工作。

The issue is that 1231.23123 cannot be represented as a float . 问题是不能将1231.23123表示为float In fact, the nearest number that can be represented as a float is 1231.231201171875 , which is what you're seeing (rounded by sprintf() to six decimal places). 实际上, 可以表示为float的最接近的数字是1231.231201171875 ,这就是您所看到的(被sprintf()舍入到小数点后六位)。

If you want a set number of digits to compare against in a string, use the precision specifier in sprintf - %.5f , and as others have pointed out, the number you've picked cannot be represented by a float , but can be represented by a double . 如果要在字符串中与一组比较的数字进行比较,请在sprintf - %.5f使用精度说明%.5f ,并且正如其他人指出的那样,您选择的数字不能用float表示,但可以表示double ie

double a = 1231.23123;
char b[32];
sprintf(b, "%.5f",a);

It's because the precision of float cannot support so many digits. 这是因为float的精度不能支持这么多数字。 So b is not "1231.23123". 因此b不是“ 1231.23123”。 In my test, it's "1231.231201". 在我的测试中,它是“ 1231.231201”。

You are comparing these 2 strings here: 您在这里比较这两个字符串:

1231.23123
1231.231201

which are different indeed, thus strcmp returns non-zero value. 的确不同,因此strcmp返回非零值。

The actual problem here is that when you do float a = 1231.23123; 这里的实际问题是,当您进行float a = 1231.23123;float a = 1231.23123; , the number you want to store in a can't be represented as a float , the nearest number that can be represented as a float is 1231.231201171875 in this case. ,您要存储在a的数字不能表示为float ,在这种情况下,可以表示为float的最接近的数字是1231.231201171875 Have a look at OMG Ponies!!! 看看OMG小马!!! (Aka Humanity: Epic Fail) ;) (又名Humanity:Epic Fail) ;)


To solve your problem I would start with using double instead of float to get more precise accuracy. 为了解决您的问题,我将首先使用double而不是float来获得更精确的精度。 Then you could specify the precision ( %.5lf ) while printing this number into the string to make sure that the number is rounded just like you need it: 然后,您可以在将此数字打印到字符串中时指定精度( %.5lf ),以确保该数字舍入为所需的数字:

double d = 1231.23123;
char str[32];
sprintf(str, "%.5lf", d);
// strcmp(str, "1231.23123") would return 0 here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM