2013-12-08 101 views
1
#include<iostream> 
#include<math.h> 
using namespace std; 

int main() 
{ 
    int temp = 0, n = 1100, x = 0, t2 = 0, l = 10; 
    while(temp < n) 
    { 
     t2 = temp; 

     temp += pow(l, ++x); 

     cout << t2 << " " << temp << " " << x <<endl; 

    } 

    return(0); 
} 

获得的输出是:意外的输出

0 10 1 
10 109 2 
109 1109 3 

但我希望输出:

0 10 1 
10 110 2 
110 1100 3 

为什么这种差异..请帮助..我不能找出问题

+3

您是否对空间过敏?可能不应该使用名为'l'的变量。看起来很像'1'。 –

+2

不知道你使用的是什么工具链,我只能用''和clang 3.3来获得预期的输出结果。 – WhozCraig

+0

你的程序在我的系统中给出正确的输出! pow函数的这个未定义的行为已经被观察了很多次! –

回答

1

请勿使用pow进行整数运算。尝试

#include<iostream> 
#include<math.h> 
using namespace std; 

int main() 
{ 
    int temp = 0, n = 1100, x = 0, t2 = 0, l = 10; 
    while(temp < n) 
    { 
     t2 = temp; 

     int t3 = 1, t4 = 0; 
     ++x; 
     while (t4++ < x) t3 *= l; 
     temp += t3; 

     cout << t2 << " " << temp << " " << x <<endl; 

    } 

    return(0); 
} 

// or alternatively 

#include<iostream> 
#include<math.h> 
using namespace std; 

int main() 
{ 
    int temp = 0, n = 1100, x = 0, t2 = 0, l = 10; 
    while(temp < n) 
    { 
     t2 = temp; 

     temp += floor(pow(l, ++x) + .5); 

     cout << t2 << " " << temp << " " << x <<endl; 

    } 

    return(0); 
} 
+0

为什么不pow功能? –

+0

@KaustavRay,因为根据实施情况,即使具有整体权力,它也可以产生近似结果。它总是产生非积分幂的近似结果。在你的情况下,可能'pow'返回的浮点数值略小于10,也许是9.99999999987。但是因为你将这个值赋给一个整数,所以编译器会隐式地将浮点数转换为整数9. – ThomasMcLeod

+0

感谢这些信息! –

0

默认pow returns double。这意味着当您使用表达式temp += pow(l, ++x);时,会出现从double到int的隐式转换,以匹配temp的类型。

双打没有确切的表示(如整数)。因此,100的双倍值可以是类似于99.999999..99832的东西。将此值转换为int时,只考虑小数点前的数字。因此,100的相应值将为99。您可以通过添加一些非常小的值(如数学中的epsilon)来纠正此问题(如数学中的epsilon):

while(temp < n) 
{ 
    t2 = temp; 
    double d = pow(l, ++x); 
    cout << (int) d << endl; 
    cout << (int) (d + 1e-10) << endl; // 1е-10 is 0.0000000001 

    temp += (int) (d + 1e-10); 
}