0
我想編寫一個程序來查看整數是否是另一個整數(真實返回1和假返回0)的功率。代碼如下:執行程序時出現一些錯誤
#include <stdio.h>
#include <math.h>
int cal_base_power(int);
int main()
{
int x,r;
printf("Please input an integer\n");
scanf("%d\n",&x);
r=cal_base_power(x);
printf("result is %d\n",r);
}
int cal_base_power(int input)
{
int i=2;
double a=pow(input,(double)1/i);
while (a>=2)
{
if ((double)a==(int)a)
return 1;
i++;
a=pow(input,(double)1/i);
}
return 0;
}
這是可以的4,8,125像這些情況。但是當輸入216和343失敗時,它也不會自動輸出0和1.在結果0或1出來之前,我必須輸入一些隨機特徵。 任何人都可以幫助我嗎?我知道這很容易。但我真的需要你的幫助
此線程應該是有用的http://stackoverflow.com/questions/295579/fastest-way-to-determine-if-an-integers-square-root-is-an-integer – Mahesh
你確定你並不意味着以'sqrt(input)'開始'a'關閉?我的意思是,那就是你在做什麼,但是你寫的代碼更復雜。儘管如此,代碼看起來實際上並沒有錯。通過我的支票。 – Borealid
'(double)a ==(int)a'這是很奇怪的,因爲浮點數的有限(巨大但仍然有限)精度,如果我是你,我會嘗試另一種解決方案...例如開始2,計算它的高低,同時 Simon