cpp 程序中的意外输出

Unexpected output in cpp program

本文关键字:意外 输出 程序 cpp      更新时间:2023-10-16
#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

为什么这种差异?..请帮忙..我找不到问题

不要将 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);
}

默认情况下,pow 返回双精度。这意味着当您使用表达式temp += pow(l, ++x);时,有一个从 double 到 int 的隐藏强制转换,以便匹配temp的类型。

双精度没有确切的表示形式(如整数(。因此,100的双精度值可以是类似 99.999999..99832 。将此值转换为 int 时,仅考虑小数点前的数字。因此,100的相应值将99 。您可以通过添加一些非常小的值(如数学中的 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);
}