[英]Prompt the user to enter time in seconds, then display it in minutes and seconds
//到目前為止我做了什么
int seconds, minutes;
Console.Write("Seconds: ");
seconds = int.Parse(Console.ReadLine());
minutes = seconds / 60;
seconds = seconds % 60;
Console.ReadLine();
似乎您只需要在ReadLine
之前將結果輸出到控制台:
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("\nPress any key to exit...");
Console.ReadKey();
此外,正如您所知,有一個System.TimeSpan
類可以為您進行這些計算。 您可以使用靜態方法FromSeconds()
創建它(還有其他方法,例如FromDays
、 FromHours
、 FromMinutes
等),然后您可以訪問TotalSeconds
或Seconds
類的屬性:
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("\nPress any key to exit...");
Console.ReadKey();
對於未來,我建議嘗試使用 Google 來做這樣簡單的事情。
Console.WriteLine(minutes + " minutes & " + seconds + " seconds");
Rufus L 的回答是准確的,但在使用int totalSeconds = int.Parse(Console.ReadLine());
時有一點警告int totalSeconds = int.Parse(Console.ReadLine());
. 用戶可以輸入字符,您的控制台應用程序將崩潰。
您可以添加 try catch bloc 來防止這種情況,如下所示:
try {
int totalSeconds = int.Parse(Console.ReadLine());
}
catch (FormatException) {
Console.WriteLine("The entered number is invalid.");
}
有更好的方法可以使用循環來做到這一點,以允許用戶再次輸入。 查看Int.TryParse(...) ,它根據解析是否成功返回一個布爾值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.