while循环错误?

时间:2014-09-15 00:33:20

标签: c++ decimal-point

我做了一个计算小数点的简单例子,但它没有停止,也没有给我正确的答案,这是我的代码:

double b=76327741.125;
int count=0;
while(b - (int)b > 0.0)
    {
        b*=10;            
        count++;          
    } 
        cout<<count;

答案应该是:

3

但是while循环一直无限运行..我的代码出了什么问题?

2 个答案:

答案 0 :(得分:1)

您应该先检查INT_MAX。数字会有所不同。这取决于您是在32位还是64位计算机上运行代码。如果它小于你的初始b,你肯定会在无限循环中结束。例如,短整数类型的最大值为32767.在这种情况下,循环的条件如下:76327741.125 - some negative number,大于0.但是,在循环中,增加了b的值。下次,当我们点击条件行时,它将是这样的:76327741.125*10 - some negative number

答案 1 :(得分:0)

您应该将b设置为b - int(b),以确保它不会持续增加(并且可能会溢出)。

double b=76327741.125;
int count=0;
while(b - (int)b > 0.0)
{
  b = b - int(b); // Note the change here.
  b*=10;
  count++;          
} 
cout<<count;