Prompt the user to enter time in seconds, then display it in minutes and seconds
我到目前为止所做的
1 2 3 4 5 6 7 8 9 | int seconds, minutes; Console.Write("Seconds:"); seconds = int.Parse(Console.ReadLine()); minutes = seconds / 60; seconds = seconds % 60; Console.ReadLine(); |
似乎您只需要将结果输出到控制台,就在
1 2 3 4 5 6 7 8 9 10 11 | Console.Write("Enter the number of seconds:"); int totalSeconds = int.Parse(Console.ReadLine()); int minutes = totalSeconds / 60; int seconds = totalSeconds % 60; // You're missing this line: Console.WriteLine($"{totalSeconds} seconds = {minutes} minutes and {seconds} seconds"); Console.Write(" Press any key to exit..."); Console.ReadKey(); |
而且,正如你所知道的,有一个
1 2 3 4 5 6 7 8 9 10 | Console.Write("Enter the number of seconds:"); int totalSeconds = int.Parse(Console.ReadLine()); var result = TimeSpan.FromSeconds(totalSeconds); Console.WriteLine( $"{result.TotalSeconds} seconds = {result.Minutes} minutes and {result.Seconds} seconds"); Console.Write(" Press any key to exit..."); Console.ReadKey(); |
使用
您可以添加Try-Catch块以防止出现这种情况:
1 2 3 4 5 6 | try { int totalSeconds = int.Parse(Console.ReadLine()); } catch (FormatException) { Console.WriteLine("The entered number is invalid."); } |
有更好的方法可以通过循环来实现这一点,以允许用户再次输入。请检查int.typarse(…),它根据分析是否成功返回布尔值。
对于未来,我建议尝试谷歌做一些简单的事情。
1 | Console.WriteLine(minutes +" minutes &" + seconds +" seconds"); |