c++ - 有人能告诉我为什么我们在 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 会得到这个答案吗?
解决方案
推荐阅读
- visual-studio-code - 如何默认打开markdown预览到底部?
- php - 两个按钮递减相同的值
- java - Postgres spring boot R2dbc应用程序中缺少DatabaseClient
- angular - 在 initializeBindings 期间尝试使用 UpgradeComponent 会导致 TypeError
- python - 有没有更好的方法来利用 redshift、python 和 powershell 来自动化我的报告?
- r - 锁定屏幕后如何在linux中运行ar代码?
- java - 如何截取屏幕截图,然后单击硒中保存的屏幕截图?
- sql-server - 如何更新表中的多个记录以从列中删除第二个单词?
- node.js - nodejs:在 http.createServer 关闭时释放资源
- python - 根据存储在 csv 中的地点/商店名称和城市检索完整地址和地理编码