我正在做以下编程练习:
编写一个程序,要求用户输入整数秒数
值(使用 long
类型,或者,如果可用,long long
)然后显示等效的
以天、小时、分钟和秒为单位的时间。用符号常量来表示
一天中的小时数,一小时中的分钟数,以及
一分钟秒。输出应如下所示:
Enter the number of seconds: 31600000
31600000 seconds = 365 days, 17 hours, 46 minutes, 40 seconds
所以我写了这个(在 Microsoft Visual Studio 2015 中):
#include "stdafx.h"
#include iostream
int main()
{
using namespace std;
const int sec_per_min = 60;
const int min_per_hr = 60;
const int hr_per_day = 24;
cout << "Enter numbers of second: ";
long long seconds;
cin >> seconds;
int day, hr, min, sec;
day = seconds / (sec_per_min * min_per_hr * hr_per_day);
hr = (seconds - day * hr_per_day * min_per_hr * sec_per_min) / (sec_per_min * min_per_hr);
sec = seconds % sec_per_min;
min = (seconds - sec) / sec_per_min % min_per_hr;
cout << seconds << " seconds = ";
cout << day << " days, ";
cout << hr << " hours, ";
cout << min << " minutes, ";
cout << sec << " seconds.";
return 0;
}
它产生了正确的结果。
但是我想知道对于 day
、hr
、min
、sec
是否有更好的语句?
最佳答案
我会做以下事情。我认为它更清楚:
auto n=seconds;
sec = n % sec_per_min;
n /= sec_per_min;
min = n % min_per_hr;
n /= min_per_hr;
hr = n % hr_per_day;
n /= hr_per_day;
day = n;
关于c++ - 将秒转换为天、小时、分钟、秒格式(C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41314888/