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当然是更好的方法了