我有一些英里数和以 MPH 为单位的速度,我已将其转换为以该速度行驶该距离所需的小时数。现在我需要将这个十进制数字转换为小时、分钟和秒。我该怎么做呢?我现在最好的猜测是:
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;
这是对的吗?有一个更好的方法吗?谢谢!
最佳答案
我根本不知道 C++ 函数,但是这个“伪代码”应该可以工作。
double time = distance / speed;
int hours = time;
double minutesRemainder = (time - hours) * 60;
int minutes = minutesRemainder;
double secondsRemainder = (minutesRemainder - minutes) * 60;
int seconds = secondsRemainder;
修正了不需要地板的问题。
关于它不适用于负时间的评论,在物理学中你不能有负距离。我想说这将是用户输入错误,而不是编码器错误!
关于C++ 将十进制小时转换为小时、分钟和秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1903846/