[英]Why is my code outputting strings multiple times in my if statement?
我的代碼多次輸出相同的字符串。 例如,輸入 40 的結果是“不!你的答案太高了。再試一次。” 兩次,它兩次顯示“你的答案太低”。
while (numberguess != 40.5)
{
numberguess = Console.Read();
if (numberguess < 40.5)
{
Console.WriteLine("Nope! Your answer is too low. Try again.");
}
else if (numberguess > 40.5)
{
Console.WriteLine("Nope! Your answer is too high. Try again.");
}
else if (numberguess == 40.5)
{
Console.WriteLine("Correct! Wow, I didn't really think you would figure it out!");
break;
}
}
我希望在輸入數字時只顯示一個字符串,並且我希望它對應於它是低於還是高於特定數字。
這一行有幾個問題:
numberguess = Console.Read();
首先它返回一個int,所以它永遠不會返回40.5。 此外,這一次讀取一個字符,包括通過 Enter 鍵輸入的字符,因此當您鍵入 40 並按 Enter 時,它會讀取“4”,然后是“0”,然后是“\\r”,最后是“\\n”(轉換這些字符到 int)。 這就是它顯示四條消息的原因。
相反,您必須使用Console.ReadLine()
讀取 Enter 之前鍵入的所有內容,然后將此(字符串)轉換為雙精度值。 所以最后你必須這樣做:
numberguess = double.Parse(Console.ReadLine());
Console.Read() 將單個字符讀取為 int。 如果您想獲取用戶在按 Enter 鍵之前輸入的內容,請閱讀當前行,然后從中解析一個整數。
int.Parse(Console.ReadLine());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.