0
        Console.Write("Type in the number of seconds: ");
        int total_seconds = Convert.ToInt32(Console.ReadLine());

        int hours = total_seconds / 3600;
        total_seconds = total_seconds % (hours * 3600);
        int minutes = total_seconds / 60;
        total_seconds = total_seconds % (minutes * 60);
        int seconds = total_seconds;
        Console.WriteLine("Number of hours: " + hours + " hours" + "\nNumber of minutes: " + minutes + " minutes" + "\nNumber of seconds: " + seconds + " seconds");
        Console.ReadLine();

设法创建一个程序,将总秒数转换为相应的小时、分钟、秒。我遇到了一个问题,因为我不希望程序也能够在 3660 以下的总秒数内显示小时数、分钟数等,这似乎是不可能的。任何想法如何帮助解决这个问题?

4

2 回答 2

3

问题出在取模数(%运算符)的行中。您想要删除所有整小时后剩下的秒数,即total_seconds % 3600. 您拥有的代码,如果您的时间低于 3600 秒,将尝试执行total_seconds % 0,即除以零。尝试以下操作:

int hours = total_seconds / 3600;
total_seconds = total_seconds % 3600;
int minutes = total_seconds / 60;
total_seconds = total_seconds % 60;
int seconds = total_seconds;
于 2012-09-26T09:03:12.920 回答
0

编辑
Chowlett 的回答更优雅地做到了这一点 - 使用他的代码。

这似乎对我有用(通过if我确保在我们为零的情况下我不会被零除hours的语句minutes

int total_seconds = 3640;

int hours = 0;
int minutes = 0;
int seconds = 0;

if (total_seconds >= 3600)
{
    hours = total_seconds / 3600;
    total_seconds = total_seconds % (hours * 3600);
}

if (total_seconds >= 60)
{
    minutes = total_seconds / 60;
    total_seconds = total_seconds % (minutes * 60);
}

seconds = total_seconds;
Console.WriteLine("Number of hours: " + hours + " hours" + "\nNumber of minutes: " + minutes + " minutes" + "\nNumber of seconds: " + seconds + " seconds");
Console.ReadLine();
于 2012-09-26T09:03:43.330 回答