在使用在整型計算中,如果次方數過大,使用 pow 會出現一些問題。
比如這兩個代碼,本質上計算是相同,並沒有什么區別。
#include <stdio.h>
#include <math.h>
int main()
{
long long s=0,a;
for (int i=1;i<=60;i++){
s+=pow(2,i-1);
}
printf("%lld",s);
return 0;
}
#include <stdio.h>
#include <math.h>
int main()
{
long long s=0,a;
for (int i=1;i<=60;i++){
a=pow(2,i-1);
s+=a;
}
printf("%lld",s);
return 0;
}
運行結果如下(不怎么會調圖片大小,就放原截圖了)
發現運行結果差1
調試中
在循環當中插入
printf("%d %lld\n",i,s);
發現是進行第54次循環時出現了問題
和同學討論,發現了原因出在哪里,並解決了這個問題
C語言 pow 的原函數是 double pow,計算的結果返回的是 double,也就是雙精度。
所以我們要自我設定一個關於 long long 類型的 pow 函數。
long long longpow(int x,int y)
{
int i;
long long p=1;
for (i=1;i<=y;i++){
p*=x;
}
return(p);
}
運行的前面兩種方式(附代碼和運行結果)
#include <stdio.h>
#include <math.h>
int main()
{
long long longpow(int x,int y);
long long s=0,a=0;
for (int i=1;i<=60;i++){
s+=longpow(2,i-1);
}
printf("%lld",s);
return 0;
}
long long longpow(int x,int y)
{
int i;
long long p=1;
for (i=1;i<=y;i++){
p*=x;
}
return(p);
}
#include <stdio.h>
#include <math.h>
int main()
{
long long longpow(int x,int y);
long long s=0,a=0;
for (int i=1;i<=60;i++){
a=longpow(2,i-1);
s+=a;
}
printf("%lld",s);
return 0;
}
long long longpow(int x,int y)
{
int i;
long long p=1;
for (i=1;i<=y;i++){
p*=x;
}
return(p);
}