Reputation: 253
I am reading in several integers, which represent the year, julian day, hour, and minutes. I am trying to convert them to fractional days.
int YYYY, JJJ, HH, MM;
float datenumber = (YYYY*360.0f)+(JJJ*1.0f)+((HH*1.0f)+(MM/60.0f))/24.0f;
Using the values of 2001, 083, 22, 32
I should get a result of 724043.939
. Instead I get 724044
.
I have all the ints cast as floats. Why do they stay as integers?
edit Yes, I was displaying the output with cout. setprecision resolved the problem, thank you.
Upvotes: 3
Views: 219
Reputation: 17732
Judging from your input and output values in the example you provided in Benjamin's answer, I am willing to bet that the issue is just floating point precision. Just because you declare something as a float, doesn't mean it can handle any size number. The problem lies in the fact that your year component (1200*360=432000) is WAY larger than your MM component(5/60/24=.00347222). The decimal portion from the MM part is just ignored because floats aren't that accurate. Try adding .000001 to 123456789 as a float and see what your output is
Upvotes: 0
Reputation: 34601
You need to do TWO things:
cout.setprecision(16)
)double
(double dateNumber
and YYYY*360.0
)Upvotes: 1
Reputation: 103693
The problem is not in your number or your calculation. It is only in the way you are displaying it. cout
has decided that 6 digits is enough for you. Use setprecision
if you want more.
std::cout << std::setprecision(10) << datenumber;
Upvotes: 3
Reputation:
The following may be the reason- 1.May be you are printing them wrongly. 2.Dividing by an integer,use float instead.
Example-Instead of dividing by 200 divide by 200.0
Upvotes: 0
Reputation: 3034
Unless you've got some more code that does the casting elsewhere, you're doing your cast after you've done the equation, so you are getting a float back, but using the ints in the equation before your cast drops the decimals.
Why not declare them as floats initially?
float YYYY, JJJ, HH, MM;
Upvotes: 0