0

所以我有这个代码

double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};

printf("%d", balance[0]);

所以我希望打印出数组的第一个元素,即 1000.0。但是,出于某种奇怪的原因,它继续打印 0。有人知道为什么吗?

4

6 回答 6

4

来自 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, ....

您需要使用正确的格式说明符来打印变量的值。

于 2013-11-13T05:02:45.307 回答
1

您正在使用 a 的格式说明符signed int来打印 a double
用这个-

printf("%f", balance[0]);

于 2013-11-13T04:55:01.903 回答
1

要打印double,请使用%f

printf("%f", balance[0]);

您可能会混淆d in 的%d意思是double,但实际上它的意思是decimal

于 2013-11-13T04:55:07.640 回答
1

要打印你不能使用的双精度值,%d你应该使用%f它。

double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};

printf("%f", balance[0]);
于 2013-11-13T05:02:05.350 回答
0

使用 %f 代替 %d。您也可以将 double 替换为 float。

浮动余额[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};

printf("%f", 余额[0])

  1. %d 用于整数。
  2. %f 用于浮点数。
于 2013-11-13T05:08:35.463 回答
0

您在代码的 printf 语句中使用了错误的格式说明符。您正在尝试使用 %d 格式说明符打印浮点值,这会导致意外输出。

使用%f代替%d一切都会好起来的,如下所示:

double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
printf("%f", balance[0]);

输出 :

1000.000000
于 2013-11-13T05:53:36.987 回答