首页 > 解决方案 > 有人能告诉我为什么我们在 C++ 中对 int 变量和 pow() 求和时会得到错误的答案吗?

问题描述

我有这个代码

#include<iostream>
#include<math.h>
using namespace std;
int main(){
    int a[10],h=0;
    a[1]=1;
    a[2]=0;
    a[3]=2;
    a[4]=5;
    for(int i=1; i<=4; i++){
        cout<<h<<" + "<<pow(a[i],2)<<" = ";
        h = h + ((int)pow(a[i],2));
        cout<<h<<"\n";
    }
    cout<<"h = "<<h;
}

结果会是这样

0 + 1 = 1
1 + 0 = 1
1 + 4 = 5
5 + 25 = 29
h = 29

但是当我们将变量更改为 double 时,我们会得到正确的答案。那么,有人可以向我解释为什么我们使用 int 会得到这个答案吗?

标签: c++intcalculation

解决方案


推荐阅读