atof()双重问题 [英] atof() to double problem

查看:163
本文介绍了atof()双重问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我正在使用VC ++ 6.0,并且atof()出现以下问题.

Hi,
I am using VC++ 6.0 and having following problem with the atof().

char test[10];
strcpy(test,"1.003");
float flTest=atof(test);
double dbTest=atof(test);


现在flTest返回1.003,但是dbTest返回1.00299999.任何人都建议为什么会发生这种情况而无法获得正确的转换吗?

谢谢
Neil


Now flTest returns 1.003, but dbTest returns 1.00299999. Anyone advice why this is happening and not getting the correct conversion?

Thanks
Neil

推荐答案

这是因为二进制数不能表示所有可能的实数.因此,当您指定无法表示的实数时,将使用其最接近的实数.

-Saurabh
This this because binary numbers cannot represent all possible real numbers. So when you specify a real number which cannot be represented then its nearest real number is used.

-Saurabh


这真的不是问题.
这只是浮点数表示的方式.

当您说退货时,实际上是在这里执行printf.
因此,如果printf("%f", dbTest);返回1.00299999,请检查printf("%.3f", dbTest);返回的内容.
This is really not an issue.
It''s just the way floating point numbers are represented.

When you say returns, you''re actually doing a printf here.
So if printf("%f", dbTest); returns 1.00299999, check what printf("%.3f", dbTest); returns.


Saurabh 所说:

这是因为二进制数不能表示所有可能的实数.因此,当您指定无法表示的实数时,将使用其最接近的实数.


另一件事:函数的两个重载不能仅靠返回值而不同.这意味着在代码段上,您始终在调用函数double atof(const char *buffer),并且编译器隐式地强制转换为float.这意味着亚当·罗德里克(Adam Roderick J)错误地断言,具有双重算术和atof函数的内幕并不奇怪.
As Saurabh said:

This this because binary numbers cannot represent all possible real numbers. So when you specify a real number which cannot be represented then its nearest real number is used.


Just another thing: there cannot exist two overloads of a functions that differ only by the return value. This means that on your code snippet, you are always calling the function double atof(const char *buffer), and the compiler implicitly casts the returned value to float. This means that there is nothing strange under the hood with double arithmetic and atof function, as Adam Roderick J erroneusly asserted.


这篇关于atof()双重问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆