使用sscanf将字符串转换为float会在C语言中产生稍微不同的结果

问题描述

我将数字字符串作为用户的输入,而不是借助sscanf()函数将其转换为float:

#include<stdio.h>

float getfloat(void);

int main()
{
    float a;
    a=getfloat();
    printf("You entered %f\n",a);
    return 0;
}

float getfloat(void)
{
    float n;
    char nstr[50];
    printf("Enter a numeric string\n");
    gets(nstr);
    sscanf(nstr,"%f",&n);
    return n;
}

现在,让我们输入一个字符串100.1234。当我在打印浮点值时借助sscanf转换为浮点数后,得到100.123398作为存储值。现在,这些值非常接近,但是为什么我得到的结果与输入的结果不一样。 sscanf内部发生了什么?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)