gpt4 book ai didi

c - 使用 printf 时出现意外结果

转载 作者:行者123 更新时间:2023-12-04 10:07:55 24 4
gpt4 key购买 nike

我看到两个程序的结果不同,我希望产生相同的输出,第一种情况:

int money;

printf("Enter the price of the car: ");
scanf("%d", &money);

printf("\nResult: %d .\n", money+money*0.4);

第二种情况:

int money;

printf("Enter the price of the car: ");
scanf("%d", &money);

money=money+money*0.4;

printf("\nResult: %d .\n", money );
return 0;

在第一种情况下 printf 的结果是 0 但在第二种情况下不是。为什么我会看到这些不同的结果?

最佳答案

%d 格式说明符告诉 printf 您正在传递 int 但在第一种情况下您传递的是 double 这也是 undefined behavior所以结果不可靠。结果:

money+money*0.4

double,因为浮点常量double,除非它有一个后缀,比如f 和结果的乘法加法也是两倍,因为通常的算术转换这两个操作都受制于和这将导致 money 的值被转换为 double 以进行操作。

在第二种情况下,您正确地传入了 int 并且因为您将结果分配给 money:

money=money+money*0.4

它将截断 double 值。我不确定您使用的是什么编译器,但是没有任何警告标志的 clanggcc 都警告格式说明符不正确,例如 gcc说:

warning: format '%d' expects argument of type 'int', but argument 2 has type 'double' [-Wformat]

因此,如果您没有看到该行的任何警告,您应该考虑将警告级别设置得更高。

为了完整起见,draft C99 standard 7.19.6.1 fprintf 函数,其中还涵盖了 printf 关于格式说明符的内容,在 9 段中说:

If a conversion specification is invalid, the behavior is undefined.248) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

关于c - 使用 printf 时出现意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19633932/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com