【问题标题】:How to repeat code line if a while loop if condition is true c#如果条件为真,如何在while循环中重复代码行c#
【发布时间】:2020-11-07 20:24:40
【问题描述】:

我需要有关以下代码的 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: ");'如果支付的金额低于价格。当前代码只会显示消息,不会提示用户再次输入价格。你能帮忙吗

【问题讨论】:

  • 只需在 num2 = line 上方的循环中重新复制 Console.Write("Paid")

标签: c# while-loop


【解决方案1】:

那是因为您希望用户一次支付价格/高于价格。看看这段代码:

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',从而在达到所需金额后结束程序。

【讨论】:

    猜你喜欢
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 2013-01-29
    • 2020-09-30
    • 1970-01-01
    相关资源
    最近更新 更多