在 coderbyte 中,它表示回傳數字為小時:分鐘,但采用整數方法。如何在 c# 中將帶冒號的數字作為時間回傳?
using System;
class MainClass {
public static int StringChallenge(int num) {
// code goes here
int hour=0;
int min ;
if (num<60)
{
min = num;
}
if (num>60)
{
min = num % 60;
hour = num / 60;
}
return "hour:min"??? ;
}
static void Main() {
// keep this function call here
Console.WriteLine(StringChallenge(Console.ReadLine()));
}
}
uj5u.com熱心網友回復:
讓TimeSpan為您完成作業:
int num = 60;
TimeSpan ts = TimeSpan.FromMinutes(num);
string formatted = ts.ToString(@"hh\:mm");
輸出一個字串
01:00
要更改格式,可以使用不同的模式。如有必要,請查看相關檔案。
uj5u.com熱心網友回復:
在這里,我采用了方法:
public static string StringChallenge(int minute)
{
return $"{minute / 60}:{minute % 60}";
}
從 59 變成“0:59”
從 60 轉變成“1:0”
從61變成“1:1”
uj5u.com熱心網友回復:
在一般情況下,我可以在這里看到兩個問題:
- 大
num,比如說num = 1600,我們想要26:40,不是1 day 2:40 - 負數:我們想要
-12:30,而不是-12:30
代碼
// Note, that we should return string, not int
// d2 - formatting - to have leading zeroes, i.e. 5:01 instead of 5:1
public static string StringChallenge(int num) =>
$"{num / 60}:{Math.Abs(num % 60):d2}";
uj5u.com熱心網友回復:
使用字串插值
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
using System;
class MainClass {
public static string StringChallenge(int num) {
Console.WriteLine(num);
// code goes here
int hour=0;
int min=0 ;
if (num<60)
{
min = num;
}
if (num>60)
{
min = num % 60;
hour = num / 60;
}
return $"{hour} : {min}";
}
static void Main() {
// keep this function call here
Console.WriteLine(StringChallenge(int.Parse(Console.ReadLine())));
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/480450.html
標籤:C#
