打印出数组元素

时间:2013-11-13 04:52:51

标签: c arrays printf

所以我有这个代码

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

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

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

6 个答案:

答案 0 :(得分: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, ....

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

答案 1 :(得分:1)

您正在使用signed int的格式说明符打印double 使用此 -

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

答案 2 :(得分:1)

要打印double,请使用%f

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

您可能会感到困惑,%d中的 d 表示 double ,但实际上它意味着十进制

答案 3 :(得分:1)

要打印您无法使用%d的双值,您应该使用%f

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

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

答案 4 :(得分:0)

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

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

printf(“%f”,balance [0])

  1. %d用于整数。
  2. %f用于浮动。

答案 5 :(得分:0)

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

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

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

输出

1000.000000
相关问题