C++ Best way to get integer division and remainder

后端 未结 8 1926
挽巷
挽巷 2020-12-01 00:29

I am just wondering, if I want to divide a by b, and am interested both in the result c and the remainder (e.g. say I have number of seconds and want to split that into minu

8条回答
  •  醉梦人生
    2020-12-01 00:53

    All else being equal, the best solution is one that clearly expresses your intent. So:

    int totalSeconds = 453;
    int minutes = totalSeconds / 60;
    int remainingSeconds = totalSeconds % 60;
    

    is probably the best of the three options you presented. As noted in other answers however, the div method will calculate both values for you at once.

提交回复
热议问题