Strange behavior of fmod()

S

Schizoid Man

I have the following code snippet where I am validating time in minutes
and hours entered in as a double variable.

If I enter the value 10.59, the value printed out is 10:58. For this
input, the correct value is being passed to 'temp', so I just can't
figure out why fmod() is misbehaving.

Any ideas?


double InputTime, temp;
int Hours, Minutes;

cout << "Enter the start time: ";
cin >> InputTime;

Hours = static_cast<int>(InputTime);
temp = InputTime - Hours;
temp = temp * 100.0;
Minutes = fmod(temp, 100);
cout << "Time is " << Hours << ":" << Minutes;
 
S

Schizoid Man

Schizoid said:
If I enter the value 10.59, the value printed out is 10:58. For this
input, the correct value is being passed to 'temp', so I just can't
figure out why fmod() is misbehaving.

Taking a closer look, it seems that this code works properly till 10.50.

For 10.50 the time is 10:50, so far so good.
For 10.51 the time is 10:50, which is very odd indeed.

I really would appreciate some help.
 
S

Schizoid Man

Schizoid said:
Taking a closer look, it seems that this code works properly till 10.50.

For 10.50 the time is 10:50, so far so good.
For 10.51 the time is 10:50, which is very odd indeed.

On further analysis, it seems that this problem only occurs if the input
is between 10.51 and 10.71.

This is very strange indeed. I really would appreciate any help at all.

Thanks.
 
P

peter koch

Schizoid said:
I have the following code snippet where I am validating time in minutes
and hours entered in as a double variable.

If I enter the value 10.59, the value printed out is 10:58. For this
input, the correct value is being passed to 'temp', so I just can't
figure out why fmod() is misbehaving.

Any ideas?


double InputTime, temp;
int Hours, Minutes;

cout << "Enter the start time: ";
cin >> InputTime;

Hours = static_cast<int>(InputTime);
temp = InputTime - Hours;
temp = temp * 100.0;
Minutes = fmod(temp, 100);
cout << "Time is " << Hours << ":" << Minutes;

You need to look-up floating-point precision.

/Peter
 
G

Gernot Frisch

double InputTime, temp;
int Hours, Minutes;

cout << "Enter the start time: ";
cin >> InputTime;

Hours = static_cast<int>(InputTime);
temp = InputTime - Hours;
temp = temp * 100.0;

Floating point representation problem.
temp = 0.5899999999999;
Minutes = fmod(temp, 100);

now Minutes = 58, which is correct.

Try:
Minutes = fmod(temp+.1, 100);

to get rid of the problem.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top