pow(),是math.h中的一個函數。通常我們用它來完成計算整數或者浮點數的n次方的操作。
但是有可能在使用的過程中有些問題需要注意,以下所有代碼編譯工具都是codeblocks。
比如下面這個簡單的代碼。
#include<cstdio>
#include<cmath>
#include<iostream>
using namespace std;
int main()
{
printf("%d\n",(int)pow(10,2));
return 0;
}
這個結果並不是100,而是99;
但是當我們把關於c++部分的頭文件註釋掉以後:
#include<cstdio>
#include<cmath>
//#include<iostream>
//using namespace std;
int main()
{
printf("%d\n",(int)pow(10,2));
return 0;
}
結果變成了100;
當我們把上面的代碼裏pow裏傳的參數提前定義爲int型的時候:
#include<cstdio>
#include<cmath>
//#include<iostream>
//using namespace std;
int main()
{
int i=10,j=2;
printf("%d\n",(int)pow(i,j));
return 0;
}
沒錯,又變成了99!
所以在使用pow函數並所傳參數是int型的時候儘量保證頭文件是c++。
當然,手寫pow當然是更好的方法了