我在 C# 中有一個程式,它從命令列獲取一個整數引數,并以下面的格式列印從 1 到該數字的數字模式,例如 5。
1
22
333
4444
55555
您可以看到,對于每個數字,該數字與它自身的列印時間相同,就像三個它在一行上列印了 3 次,依此類推。我試圖開發一個函式,它將一個整數與一個字串相乘String.Concat(string param, int n),并將該字串回傳給另一個函式,該函式有一個回圈,將預期的輸出列印到終端。我的代碼列印如下
11
22
33
44
55
對于像 5 這樣的示例整數輸入。我做錯了什么,我應該怎么做才能更正我的回圈,以便它給我預期的輸出,謝謝。
代碼
static string MakeALine(int k){
//all this function does is to convert the integer argument to string and multiply it with itself and returns it
return String.Concat(k.ToString,k);
}
//the function below contains a loop that should invoke the make a line correctly to achieve the desired output above
static string MakeLines(int arg){
//the arg is the command line argument supplied
string outp="";
//i have a problem in the loop below, please help
for(int k=1;k<=arg;k ){
//call makeALine and pass k as argument and append to the return string
outp =MakeALine(k) "\n";
}
return outp;
}
我做錯了什么,謝謝。
uj5u.com熱心網友回復:
問題出在MakeALine方法上。您實際上將數字與自身連接起來,因此對于輸入,1您實際上得到"1" "1".
相反,您應該重復數字的字串表示形式k。為此,您可以通過Enumerable.Repeat以下方式使用:
static string MakeALine(int k)
{
return String.Concat(Enumerable.Repeat(k.ToString(),k));
}
uj5u.com熱心網友回復:
試試這個:
private static string makeLines(int k)
{
string outPut = "";
for(int i = 1 ; i < k 1 ; i )
{
outPut = string.Concat(Enumerable.Repeat(i, i)) "\n";
}
return outPut;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/454231.html
