将秒转换为分钟、小时和天

Mel*_*ner 3 c# winforms

我们最近在课堂上讨论了“if 语句等……”,但我在这个问题上遇到了麻烦。(为我糟糕的英语道歉)

这是问题:

  • 创建一个允许用户输入秒数的应用程序,其工作方式如下:
  • 一分钟有 60 秒。如果用户输入的秒数大于或等于 60,则程序应显示该秒数中的分钟数。
  • 一小时有 3,600 秒。如果用户输入的秒数大于或等于 3,600,则程序应显示该秒数中的小时数。
  • 一天有 86,400 秒。如果用户输入的秒数大于或等于 86,400,则程序应显示该秒数中的天数。

这是我充满错误的答案:

    private void button1_Click(object sender, EventArgs e)
    {       
            //Declaring Variables
            int totalSeconds;
            int hours;
            int minutes;
            int minutesRemainder;
            int hoursRemainderMinutes;
            int hoursRemainderSeconds;

            // Parsing and calculations

            totalSeconds = int.Parse(textBox1.Text);
            minutes = totalSeconds / 60;
            minutesRemainder = totalSeconds % 60;
            hours = minutes / 60;
            hoursRemainderMinutes = minutes % 60;
            hoursRemainderSeconds = hoursRemainderMinutes % 60;

            if (totalSeconds >= 60)
            {
                MessageBox.Show(totalSeconds.ToString());
            }

            else if (totalSeconds >= 3600)
            {

                MessageBox.Show(minutes.ToString() + " minutes, " + minutesRemainder.ToString() + " seconds");
            }

            else if (totalSeconds >= 84600)
            {
                MessageBox.Show(hours.ToString() + " hours, " + hoursRemainderMinutes.ToString() + " minutes, " + hoursRemainderSeconds.ToString() + " seconds");


        }
    }
}
Run Code Online (Sandbox Code Playgroud)

}

运行时,我的程序不计算任何东西。我究竟做错了什么?

ser*_*iyb 5

您应该使用TimeSpan.FromSeconds 方法

它将为您提供TimeSpan结构实例,您可以在其中访问:

  • TotalDays
  • TotalHours
  • TotalMinutes

特性。

编辑

他们在评论中说你想在不使用任何库的情况下实现这一目标。那么方法是(就你的任务而言):

int totalSeconds = ....;///
int totalMinutes = totalSeconds / 60;
int totalHours = totalMinutes / 60;
int totalDays = totalHours / 24;

if (totalDays > 0){
 //show days
} else if (totalHours > 0){
  //show hours
} else if (totalMinutes > 0){
  //show minutes
} else {
  //show seconds
}
Run Code Online (Sandbox Code Playgroud)