C++ 将十进制小时转换为小时、分钟和秒

标签 c++ time decimal

我有一些英里数和以 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/

相关文章:

c++ - 如何为标准输出设置控制台光标位置

c++ - std::vector 初始化的模板参数

c++ - 如何将模板从 C++ 转换为 C

python - decimal.InvalidOperation 在 Series 中四舍五入值时出错

iphone - iOS 中的当前和更新时间?

android - EditText 始终显示带 2 位小数的数字

c++ - 通过 int 变量设置 char[] 的大小

c++ - 覆盖线程函数c++

mysql - 将 MySQL 字符串转换为时间

python - 如何以 UTC 获取当前时间(现在)?