How do I round numbers in Java?

For this program, I write the number of minutes I am accepting user input, and then round it to the next hour

>1 minute = 1 hour > 59 minutes = 1 hour > 60 minutes = 1 hour > 61 minutes = 2 hours > 119 minutes = 2 hours > 120 minutes = 2 hours > 121 minutes = 3 hours

Is there any simple way to solve this problem? thank you.

Solution

Assuming that it is an integer, it will be truncated during partition. This is a simple problem:

int hours = (minutes + 59) / 60;

The following table shows the results:

minutes                   hours
-------   ----------------------------------------
    1     (  1 + 59) / 60   ->    60 / 60   ->   1
   59     ( 59 + 59) / 60   ->   118 / 60   ->   1
   60     ( 60 + 59) / 60   ->   119 / 60   ->   1
   61     ( 61 + 59) / 60   ->   120 / 60   ->   2
  119     (119 + 59) / 60   ->   178 / 60   ->   2
  120     (120 + 59) / 60   ->   179 / 60   ->   2
  121     (121 + 59) / 60   ->   180 / 60   ->   3
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>