我的代码是:
#include<stdio.h>
#include<math.h>
int main()
{
int c = pow(3,2);
printf("%f %f %d \n\n",pow(3,2),c,c);
printf("%f %d %f \n\n",pow(3,2),c,c);
return 0;
}
输出结果为:
9.000000 0.000000 4200688
9.000000 9 0.000000
任何人都可以解释为什么在输出的第一行而不是打印9(就像它在第二行输出中那样)它会打印4200688(可能是垃圾值)?
答案 0 :(得分:1)
您提到的代码未定义的行为。阅读pow
功能的手册页并查看它的原型。它说
double pow(double x,double y);
在本声明中
int c = pow(3,2);
使用正确的格式说明符,在编译-Wall
标志时不要使用编译器警告,请听警告。
warning: format ‘%f’ expects argument of type ‘double’, but argument 3 has type ‘int’ [-Werror=format=]
printf("%f %f %d \n\n",pow(3,2),c,c);
warning: format ‘%f’ expects argument of type ‘double’, but argument 4 has type ‘int’ [-Werror=format=] printf("%f %d %f \n\n",pow(3,2),c,c);
来自C99标准第7.19.6.1节
如果任何参数不是相应的正确类型 转换规范,行为未定义。