3 回答

TA貢獻1818條經驗 獲得超8個贊
static void Main(string[] args)
{
int Nummer;
bool herhaal = true;
do
{
Console.Write("Geef een getal : ");
//only read from the Console ONCE per loop iteration, and always read to a string first
string input = Console.ReadLine();
//TryParse better than Convert for converting strings to integers
if (!int.TryParse(input, out Nummer))
{
Console.WriteLine("0");
}
else //only do the second part if the conversion worked
{
double kw = Math.Pow(Nummer, 2);
Console.WriteLine("Kwadraat van {0} is: {1}\n", Nummer, kw);
}
} while (herhaal);
}
要從 WinForms 應用程序執行此操作,如評論中所嘗試:
private void button1_Click(object sender, EventArgs e)
{
double aantalgroep;
if (!double.TryParse(textBox1.Text, out aantalgroep))
{
textBox1.Text = "0";
}
else
{
double kw = Math.Pow(aantalgroep, 2);
textBox1.Text = String.Format("Kwadraat van {0} is: {1}", aantalgroep, kw);
}
}

TA貢獻1780條經驗 獲得超5個贊
根據 C# 文檔,Console.ReadLine
執行以下操作
從標準輸入流中讀取下一行字符。
這意味著每次調用時Console.ReadLine
,都會從控制臺讀取一個新行。從我在你的代碼中看到的,這不是你想要的行為。要解決您的問題,您應該將 的結果存儲Console.ReadLine
在一個變量中并使用該變量而不是 ReadLine 方法。
- 3 回答
- 0 關注
- 217 瀏覽
添加回答
舉報