C ++将十进制小时转换为小时,分钟和秒 [英] C++ convert decimal hours into hours, minutes, and seconds

查看:168
本文介绍了C ++将十进制小时转换为小时,分钟和秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MPH中有一些英里数和一个速度,我将其转换成以该速度行驶该距离所花费的小时数。现在,我需要将此十进制数转换为小时,分钟和秒。我该怎么做呢?我现在最好的猜测是:

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 ++函数是我的首要任务,但是这种伪代码应该可以工作。 / p>

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;

更正不需要下限。

As只要有关它的评论不能在负数时间内起作用,物理学上就不能有负数的距离。我想这将是用户输入错误,而不是编码器错误!

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!

这篇关于C ++将十进制小时转换为小时,分钟和秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆