(請先看置頂博文)本博打開方式,請詳讀_liO_Oil的博客-CSDN博客_怎么把androidstudio卸載干凈
編寫程序,求sum=1*1*1+2*2*2+3*3*3+4*4*4+5*5*5+····+n*n*n
上述題目很簡單,但是偶爾也會犯錯誤,例如如下代碼的錯誤:
#include<stdio.h>
#include<math.h>
int main()
{int n;scanf("%d",&n);int s=0;int i=1;for(i=1;i<=n;i++)s=s+pow(i,3);printf("%d\n",s);return 0;
}

其真實結果應該為2732409,那為什么會有“6”的差距呢?
實際上就出現在“int”和“double”上的差距了,是因為int是整形定義,當輸入的n的值為57時,超過了其最大范圍,所以才有“6”的差距。
所以正確的代碼是:
#include<stdio.h>
#include<math.h>
int main()
{int n;scanf("%d",&n);double s=0;int i=1;for(i=1;i<=n;i++)s=s+pow(i,3);printf("%.0f\n",s);return 0;
}
