問題是我必須做一個控制檯應用程序,我輸入一個數字,它寫出符號「|」儘可能多的我插入。例如,如果我插入數字6它寫出||||||。它一直詢問,直到我插入0並關閉。到目前爲止,輸入是這樣的:輸入字符
int input;
Console.Write("\n\n Insert an number ---> ");
input = Convert.ToInt32(Console.ReadLine());
我已經嘗試使用char數組,但沒有用。
問題是我必須做一個控制檯應用程序,我輸入一個數字,它寫出符號「|」儘可能多的我插入。例如,如果我插入數字6它寫出||||||。它一直詢問,直到我插入0並關閉。到目前爲止,輸入是這樣的:輸入字符
int input;
Console.Write("\n\n Insert an number ---> ");
input = Convert.ToInt32(Console.ReadLine());
我已經嘗試使用char數組,但沒有用。
循環是那麼2012 :)
using System;
using System.Linq;
internal class Program
{
private static void Main(string[] args)
{
Enumerable.Range(0, Int32.MaxValue)
.Select(i => Int32.TryParse(Console.ReadLine(), out i) ? i : -1)
.Where(i => i >= 0)
.TakeWhile(i => i > 0)
.Select(i => {
Console.WriteLine(String.Join("", Enumerable.Repeat("|", i)));
return 0;})
.Count();
}
}
描述(即使答案是非常不嚴肅):
Enumerable.Range
是讓半無限(克里斯·辛克萊指出,這只是2,147,483,647次)枚舉有大部分單個語句的代碼。Select
逐行讀取輸入並將有效輸入轉換爲整數,其餘爲-1(請注意,在此示例中-1是「無效輸入」的可能值,通常會返回Tuple<int, bool>
或int?
來表示無效值Where
過濾掉「無效」的輸入(輸入正確負數以及所有非數字,其中爲-1通過以前報道Select
)。TakeWhile
提供終止條件爲0Select
打印結果。請注意,要從相同字符的多個副本構造字符串應該使用適當的new String("|", count)
構造函數,但它不那麼有趣。Count
強制立即重複查詢。僞代碼
is read line a number
until read line is 0
for 1 to the number
print |
is read line a number
if not a number go back at asking the number saying it is not a number
if not a number go back at asking the number saying it is not a number
現在有樂趣做作業
拖基本概念,你應該知道
for循環:
for(int i=0; i<input; i++)
{
// do stuff
}
這是做某事的常見模式input
次,所以如果input
等於6
,那麼它會比//do stuff
大6倍。
控制檯。寫
Console.Write('|');
Console.Write
寫入文本控制檯沒有將在末處加入一個新行。
我確定您可以將某些語言功能以某種方式組合起來,以滿足您的要求。
非常感謝。我用它並使用Do While循環。 :) –
那麼,你用char數組方法得到了多少?你的代碼是什麼樣的?目前,這聽起來像是你想讓我們爲你做你的功課... –
你讀過「循環」一章嗎? – I4V
我可能會用循環 –