c - 改变格式说明符的位置如何改变 ac 程序的输出?
问题描述
我的代码是:
#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 (可能是垃圾值)?
解决方案
您提到的代码具有未定义的行为。阅读pow
功能手册页并检查它的原型。它说
双 pow(双 x,双 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 节
如果任何参数不是相应转换规范的正确类型,则行为未定义。
推荐阅读
- google-api - 如何通过 API 以编程方式启用服务帐户中的“启用 G Suite 域范围委派”复选框
- javascript - 使画布拉伸以适合图像
- javascript - 如何检查 URL 是否与当前页面和/或工作人员的来源相同
- cordova - 离子 3 本地地理编码器。找不到“thoroughfare”、“subThoroughfare”
- node.js - NODE_SHARED_MODE 和 __POSIX__
- excel - 将一系列单元格剪切/粘贴到另一张工作表中并发送电子邮件
- angular - 当我创建表单 angular2 错误是显示找不到名称“产品”?
- vue.js - vuetify 组件中的 Vue Component 属性
- ios - 具有自动调整单元大小的集合视图在重新加载后停止工作
- r - 根据另一列中的值重塑状态列