循环中显示0的问题。 [英] Problem with display 0 in loop.

查看:71
本文介绍了循环中显示0的问题。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,



我试图创建简单的while循环,直到我的变量为0.

所以创建了一个

  
{
x = x + 0 001 ;
cout<< x0<< ENDL;
} while SOME_CALCULATION != 0 );





一切正常,直到我的循环达到0然后我得到7.63278e-017而不是0.



循环示例:



< br /> 
结果:-0.003< br />
结果:-0.002< br />
结果:-0.001< br />
结果:7.63278e-017< br />
结果:0.001< br / >
结果:0.002< br />
结果:0.003< br />

解决方案

你应该只知道浮点类型不代表实数(实数中,数字通常代表无限量的信息;这是无法在计算机中的有限状态机中表示的东西:-));它们代表了一些近似



我记得,在Donald E. Knuth最着名的书中, The Art计算机编程,Knuth警告读者不要在浮点类型上使用相等比较('==',在C / C ++ / C#术语中)。相反,您可以使用 fabs(value1 - value2)< someSmallNumber; 其中 someSmallNumber 由特定问题定义, fabs 是:

http://www.cplusplus.com/reference/cmath/fabs [< a href =http://www.cplusplus.com/reference/cmath/fabstarget =_ blanktitle =New Window> ^ ]。



在你的情况下,它是而(fabs(SOME_CALCULATION)< someSmallNumber)



请参阅:

http://en.wikipedia.org/wiki/The_Art_of_Computer_Programming [ ^ ],

http://en.wikipedia.org/wiki/Donald_Knuth [ ^ ]。



-SA

Hello,

Am trying to create simple while loop until my variable will be 0.
So am created a

do
{
x = x + 0.001;
cout << x0 << endl;
} while (SOME_CALCULATION != 0);



Everything works great until my loop reach 0 then i getting 7.63278e-017 instead of 0.

Loop example:

<br />
result: -0.003<br />
result: -0.002<br />
result: -0.001<br />
result: 7.63278e-017<br />
result: 0.001<br />
result: 0.002<br />
result: 0.003<br />

解决方案

You should just understand that floating-point types do not represent real numbers (in real numbers, a number generally represents infinite amount of information; this is something which cannot be represented in a finite-state machine like a computer :-)); they represent some approximation.

As I remember, in the most well-known book by Donald E. Knuth, The Art of Computer Programming, Knuth warned the readers against using equality comparison ('==', in C/C++/C# terms) on floating-point types. Instead, you can use fabs(value1 - value2) < someSmallNumber; where someSmallNumber is defined by a particular problem, and fabs is this:
http://www.cplusplus.com/reference/cmath/fabs[^].

In your case, it would be while (fabs(SOME_CALCULATION) < someSmallNumber).

Please see also:
http://en.wikipedia.org/wiki/The_Art_of_Computer_Programming[^],
http://en.wikipedia.org/wiki/Donald_Knuth[^].

—SA


这篇关于循环中显示0的问题。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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