如何使用模数将秒转换为小时分和秒?

我的老师分配了我这个作业,提示是“写一个允许用户输入秒数的程序。该程序应计算等效的小时,分​​钟和秒数。例如:9999秒= 2小时,46分39秒。Mod是您的朋友。我正在尝试与此一起使用JOptionPane。

我尝试了很多其他方法,但是没有一个起作用。当我输入2时,结果为2小时。

我希望当我输入2时,结果是2秒,而不是数小时!

ingkao84 回答:如何使用模数将秒转换为小时分和秒?

我怀疑您想执行以下操作: 给定n秒,var小时,var分钟,var秒

seconds = n%60;
minutes = (n-seconds)%3600;
//we use subtract seconds that have already been allocated
//Mod by 3600 here because this is the number of seconds in 1 hour,so the remainder will not fit into an hour
minutes = minutes/60; //convert seconds to minutes
hours = (n - minutes*60 - seconds) / 3600; //seconds remaining/seconds in an hour

此解决方案使用mod可以工作2秒钟。您可能需要添加一些条件IF语句,以确保不会因除0而失败。

本文链接:https://www.f2er.com/3157999.html

大家都在问