我正在使用代码块来学习c.我的代码是
#include<stdio.h>
#include<math.h>
int main()
{
int x;
x = pow(5,2);
printf("%d", x);
}
Output is 25
Run Code Online (Sandbox Code Playgroud)
当我使用此代码时
#include<stdio.h>
#include<math.h>
int main()
{
int x,i,j;
printf("please enter first value");
scanf("%d", &i);//5
printf("please enter second value");//2
scanf("%d", &j);
x = pow(i,j);
printf("%d", x);
}
Output is 24
Run Code Online (Sandbox Code Playgroud)
这有什么不对?我只是使用扫描功能获取价值,并以同样的方式使用pow功能.
我怀疑你有一个天真的实现pow在你libm(我得到25,因为它应该是).如果计算pow(x,y)为exp(y*log(x))正x,但不检查(小)整体指数和特别对待他们,你会得到
Prelude> 2 * log 5
3.2188758248682006
Prelude> exp it
24.999999999999996
Run Code Online (Sandbox Code Playgroud)
一个double结果比25稍小,因此,当被转换到int它被截断为24.
要检查,请将结果分配pow(i,j)给a double并打印出来.
使用硬编码pow(5,2),编译器(很可能,即使没有优化也是gcc所做的)在编译期间精确计算结果.