简体   繁体   中英

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

I have a program that uses this popular library , however I am struggling to use it to convert from seconds to minutes

The following code...

#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;
}

produces...

1 minute is 60 s
1 second is 1 s

however, I would have expected it to produce...

1 minute is 60 s
1 second is .016666667 m

I don't know the library you are using, but C++11 added the std::chrono::duration class that seems to be able to do what you want:

#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;
}

Note that the default std::chrono::minutes uses an integer counter, and thus reports that 1 second is 0 minutes. That is why I define my own float-minutes.

In any case, the above program produces the following output:

1 minute is 60
1 second is 0.0166667

The library offers a units::convert method, check the doc here .

Here's a working snippet:

    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;

For more, I suggest searching in the doc .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM