Reputation: 173
So I have this code
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
printf("%d", balance[0]);
So I expect the first element of the array to print out, which would be 1000.0. However, it keeps on printing 0 for some odd reason. Anyone have an idea on why??
Upvotes: 0
Views: 139
Reputation: 3
You have used the wrong format specifier in the printf statment in your code. You are trying to print a floating point value using the %d format specifier which results in unexpected output.
Use %f in place of %d and everything will be all right, like this :
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
printf("%f", balance[0]);
Output :
1000.000000
Upvotes: 0
Reputation: 9
Use %f instead of %d.You can also replace double with float.
float balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
printf("%f", balance[0])
Upvotes: 0
Reputation: 6606
From C11 draft
§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, ....
You need to use correct format specifier to print the value of variable.
Upvotes: 4
Reputation: 130
to print the double value you can not use %d
you should use %f
for that.
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
printf("%f", balance[0]);
Upvotes: 1
Reputation: 122503
To print double
, use %f
:
printf("%f", balance[0]);
You may be confused that d in %d
means double, but actually it means decimal.
Upvotes: 1
Reputation: 965
You are using the format specifier of a signed int
to print a double
.
Use this-
printf("%f", balance[0]);
Upvotes: 1