[英]How to repeat code line if a while loop if condition is true c#
我需要有關以下代碼的 while 循環的幫助:
using System;
namespace Sample
{
class Program
{
static int Main(string[] args)
{
int num1;
int num2;
//This collects the price as input from the user
Console.Write("Enter Price: ");
num1 = Convert.ToInt32(Console.ReadLine());
//This collects the amount paid as input from the user
Console.Write("Paid: ");
num2 = Convert.ToInt32(Console.ReadLine());
decimal price = num2 - num1;
Console.WriteLine("{0} - {1} = {2}", num2, num1, num2 - num1);
while (num2 < num1)
{
Console.WriteLine("You have paid less than the price");
Console.WriteLine("\nPlease pay an amount equals to/greater than "+num1);
num2 = Convert.ToInt32(Console.ReadLine());
}
return num2 = Convert.ToInt32(Console.ReadLine());
}
}
}
我希望代碼顯示消息並再次詢問用戶輸入 'Console.Write("Paid:");' 如果支付的金額低於價格。 當前代碼只會顯示消息,不會提示用戶再次輸入價格。 你能幫忙解決這個問題嗎
那是因為您希望用戶立即支付價格/高於價格。 看看這段代碼:
static void Main(string[] args)
{
int price;
int paid;
//This collects the price as input from the user
Console.Write("Enter Price: ");
price = Convert.ToInt32(Console.ReadLine());
//This collects the amount paid as input from the user
Console.Write("Paid: ");
paid = Convert.ToInt32(Console.ReadLine());
decimal change = paid - price;
Console.WriteLine("{0} - {1} = {2}", paid, price, change);
while (paid < price)
{
Console.WriteLine("You have paid less than the price");
Console.WriteLine("\nPlease pay an amount equals to/greater than " + price);
paid += Convert.ToInt32(Console.ReadLine());
Console.WriteLine("You have paid:" +paid);
}
Console.WriteLine("You have paid enough, the price was {0} and you paid {1}", price, paid);
}
我已經更改了變量名稱,使其更清楚發生了什么。 使用此代碼,您將新輸入添加到上次輸入中,因此最終變量 'paid' 將大於變量 'price',從而在達到所需金額后結束程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.