c++ - 将秒转换为天、小时、分钟、秒格式(C++)

标签 c++

我正在做以下编程练习:

编写一个程序,要求用户输入整数秒数 值(使用 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;
}

它产生了正确的结果。 但是我想知道对于 dayhrminsec 是否有更好的语句?

最佳答案

我会做以下事情。我认为它更清楚:

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/

相关文章:

c++ - std::make_from_tuple 在没有构造函数的情况下无法编译

c++ - 是否可以将方法参数的类型定义为类或任何派生类?

c++ - 为什么 C++ 中的这个 lambda 包含每个引用?

c++ - 为什么要在 C++ 中使用虚函数?

c++ - 解决 "only static const integral data members can be initialized within a class"编译错误

c++ - C++ 教程上的机器语言指令

c++ - 在 boost transformed() 之后比较嵌套迭代器

c++ - 使用继承在 C++ 中调用析构函数和销毁成员变量的顺序是什么?

C++(和 openCV): Accumulating a number of Mat in vector<Mat>

c++ - 声明使用 C 代码的 c++ 类的多个实例