本文介绍了字符串比较Ç - STRCMP()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我试图比较2字符串,但我失败了实现这一目标,为什么?

 的#include<&stdio.h中GT;
#包括LT&;&string.h中GT;
诠释主(){
    浮动= 1231.23123;
    焦B〔32〕;
    sprintf的(B,%F,一);
    的printf(%S \\ n,B);
    焦C [32] =1231.23123;
    如果(的strcmp(C,B)== 0){
        的printf(SUCCES \\ n);
    }
    其他{
        的printf(DIFFER的\\ n);
    }
    返回0;
}

结果:

  1231.231201
不同


解决方案

两个字符串显然是不同的,所以的strcmp()工作,因为它应该。

问题是, 1231.23123 不能重新presented为浮动。事实上,最接近的数字可以的是psented为浮动重新$ P $是 1231.231201171875 ,也就是你看到的(通过的sprintf() 6位小数)。

Hello I'm trying to compare 2 string, 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.

The issue is that 1231.23123 cannot be represented as a 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).

这篇关于字符串比较Ç - STRCMP()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 22:41