C++ convert decimal hours into hours, minutes, and

2019-05-22 20:21发布

I have some number of miles and a speed in MPH that I have converted into the number of hours it takes to travel that distance at that speed. Now I need to convert this decimal number into hours, minutes, and seconds. How do I do this? My best guess right now is:

double time = distance / speed;
int hours = time; // double to integer conversion chops off decimal
int minutes = (time - hours) * 60;
int seconds = (((time - hours) * 60) - minutes) * 60;

Is this right? Is there a better way to do this? Thanks!

标签: c++ time decimal
4条回答
Luminary・发光体
2楼-- · 2019-05-22 20:24

I'd say you've got it right. :-)

Though I should add, if a method like that Aequitarium Custos has presented is more readable or preferable to you, by all means use that method. Sometimes it's easier to calculate data elements one at a time, and calculate the next one from the one you just calculated, rather than using an absolute formula always beginning from your first datum.

In the end, as long as your math is correct (and I think it is), it's up to you how you want to write the code.

查看更多
做自己的国王
3楼-- · 2019-05-22 20:36

a. Check if speed is not 0

b. it is bad programming to put a double into an int IMHO. use floor (assuming time is positive...)

c. if speed and distance are int - the result in time will be wrong...

d. @Aequitarum Custos got it right after the edit...

查看更多
可以哭但决不认输i
4楼-- · 2019-05-22 20:37

I don't know c++ functions off the top of my head, however this "psuedocode" should work.

double time = distance / speed;
int hours = time;
double minutesRemainder = (time - hours) * 60;
int minutes = minutesRemainder;
double secondsRemainder = (minutesRemainder - minutes) * 60;
int seconds = secondsRemainder;

Corrected not needing floor.

As far as the comment about it not working for negative times, you can't have a negative distance in physics. I'd say that would be user input error, not coder error!

查看更多
男人必须洒脱
5楼-- · 2019-05-22 20:37

I don't know if this is better...actually I don't know for sure that it is right as I haven't tested it, but I would first convert the hours to the total number of seconds, then convert that back into hours/minutes/seconds. It would look something like:

int totalseconds = time * 3600.0;

// divide by number of seconds in an hour, then round down by casting to an integer.
int hours = totalseconds/3600;

// divide by 60 to get minutes, then mod by 60 to get the number minutes that aren't full hours
int minutes = (totalseconds/60) % 60;  

// use mod 60 to to get number of seconds that aren't full minutes
int seconds = totalseconds % 60;  
查看更多
登录 后发表回答