如何使用此库将秒数转换为分钟数?

How do I convert from seconds to minutes using this library?

我有一个 program that uses this popular library,但是我很难用它来将秒数转换为分钟数

以下代码...

#include <iostream>

#include "units.h"

int main(int argc, const char * argv[])
{
    {
        long double one = 1.0;

        units::time::second_t seconds;
        units::time::minute_t minutes(one);

        seconds = minutes;

        std::cout << "1 minute is " << seconds << std::endl;
    }


    {
        long double one = 1.0;

        units::time::second_t seconds(one);
        units::time::minute_t minutes;

        minutes = seconds;

        std::cout << "1 second is " << minutes << std::endl;
    }

    return 0;
}

产生...

1 minute is 60 s
1 second is 1 s

然而,我本以为它会产生...

1 minute is 60 s
1 second is .016666667 m

我不知道你用的是什么库,但是 C++11 添加了 std::chrono::duration class 似乎可以做你想做的事:

#include <chrono>
#include <iostream>
int main()
{
    {
        std::chrono::minutes minutes(1);
        std::chrono::seconds seconds;

        seconds = minutes;

        std::cout << "1 minute is " << seconds.count() << std::endl;
    }

    {
        std::chrono::seconds seconds(1);
        using fMinutes = std::chrono::duration<float, std::chrono::minutes::period>;
        fMinutes minutes = seconds;

        std::cout << "1 second is " << minutes.count() << std::endl;
    }

    return 0;
}

请注意,默认值 std::chrono::minutes 使用整数计数器,因此报告 1 秒为 0 分钟。这就是我定义自己的浮点数的原因。

在任何情况下,上述程序都会产生以下输出:

1 minute is 60
1 second is 0.0166667

图书馆提供了一个units::convert方法,查看文档here

这是一个工作片段:

    long double one = 1.0;

    units::time::second_t seconds(one);
    units::time::minute_t minutes;

    minutes = seconds;

    std::cout << "1 second is " << minutes << std::endl;
    std::cout << "1 second is "
              << units::convert<units::time::seconds, units::time::minutes>(seconds)
              << std::endl;

有关更多信息,我建议在 doc 中搜索。