Hak*_*mez 2 c printf type-conversion undefined-behavior
我看到两个程序的不同结果,我期望产生相同的输出,第一种情况:
int money;
printf("Enter the price of the car: ");
scanf("%d", &money);
printf("\nResult: %d .\n", money+money*0.4);
Run Code Online (Sandbox Code Playgroud)
第二种情况:
int money;
printf("Enter the price of the car: ");
scanf("%d", &money);
money=money+money*0.4;
printf("\nResult: %d .\n", money );
return 0;
Run Code Online (Sandbox Code Playgroud)
在第一种情况下,结果printf是0但不是在第二种情况下.为什么我看到这些不同的结果?
该%d格式说明会告诉printf你是传递一个INT,但在第一种情况下,你传递一个双,这也是不确定的行为,因此,结果是不可靠的.的结果:
money+money*0.4
Run Code Online (Sandbox Code Playgroud)
是双由于浮动常数是双除非它有一个后缀,如f和的结果的乘法和加法是双以及由于通常的算术转换这两种操作都受到和这将导致的值money转换为双操作.
在第二种情况下,您正确地传入int,因为您要将结果分配给money:
money=money+money*0.4
Run Code Online (Sandbox Code Playgroud)
它将截断double值.我不知道你使用的编译器,但双方clang并gcc没有任何警告标志都警告不正确的格式说明,gcc例如说:
警告:格式'%d'需要类型为'int'的参数,但参数2的类型为'double'[-Wformat]
因此,如果您没有看到该线路的任何警告,您应该考虑设置更高的警告级别.
为了完整起见,草案C99标准部分7.19.6.1 fprintf功能,也包括printf格式说明符,在第9段中说:
如果转换规范无效,则行为未定义.248)如果任何参数不是相应转换规范的正确类型,则行为未定义.