Reputation: 5
Okay, so I have a this equation here that's suppose to get close to the value of pi, but for some reason, my double value is always being converted to a whole number. For example, one of my number is 1/3 but when I print it out, it becomes 0.0. Is it because you have to add d to the end of double values? If so, how would I add it to the end of something like this:
fractionpart = fractionpart + (1/i)
Upvotes: 0
Views: 72
Reputation: 98338
A D
is not used for double constants in C, they are double by default, but a .
is. That is, 1
is an integer, while 1.
is a double (1.F
is a float, BTW, and 1.L is a long double, if it is supported by your compiler).
I personally prefer to add a 0
after the .
because 1.
looks like the end of an English sentence, while 1.0
looks like a proper number. The leading 0 is also optional, so you can write for example .1
, but I prefer 0.1
.
So your calculation can be written as:
fractionpart = fractionpart + 1.0 / i;
The alternative would be to add a cast to make the type explicit:
fractionpart = fractionpart + 1 / (double)i;
You can cast any of the two operands of the division.
Upvotes: 1