所以我有这个代码
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
printf("%d", balance[0]);
所以我希望打印出数组的第一个元素,即 1000.0。但是,出于某种奇怪的原因,它继续打印 0。有人知道为什么吗?
来自 C11 草案
§7.16.1.1/2
...if type is not compatible with the type of the actual next argument
(as promoted according to the default argument promotions), the behavior
is undefined, ....
您需要使用正确的格式说明符来打印变量的值。
您正在使用 a 的格式说明符signed int
来打印 a double
。
用这个-
printf("%f", balance[0]);
要打印double
,请使用%f
:
printf("%f", balance[0]);
您可能会混淆d in 的%d
意思是double,但实际上它的意思是decimal。
要打印你不能使用的双精度值,%d
你应该使用%f
它。
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
printf("%f", balance[0]);
使用 %f 代替 %d。您也可以将 double 替换为 float。
浮动余额[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
printf("%f", 余额[0])
您在代码的 printf 语句中使用了错误的格式说明符。您正在尝试使用 %d 格式说明符打印浮点值,这会导致意外输出。
使用%f代替%d一切都会好起来的,如下所示:
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
printf("%f", balance[0]);
输出 :
1000.000000