繁体   English   中英

C# do while 循环 - 如何记住用户输入?

[英]C# do while loops - How to remember user input?

我是 C# 新手,我正在编写一个 do while 循环,该循环继续要求用户输入“价格”,直到他们输入“-1”作为价格。

之后,我需要将他们输入的所有价格值相加,并将其声明为小计。

我遇到的问题是它只记住最后输入的数字,即 -1。 我该怎么做才能解决这个问题?

using System;

namespace ConsoleApp1
{
class Program
{
    static void Main()
    {
        Console.WriteLine("Your Receipt");
        Console.WriteLine("");
        Console.WriteLine("");

        decimal count;
        decimal price;
        decimal subtotal;
        decimal tax;
        decimal total;

        count = 1;

        do
        {
            Console.Write("Item {0} Enter Price: ", count);
            ++count;
            price = Convert.ToDecimal(Console.ReadLine());


        } while (price != -1);

        subtotal = Convert.ToInt32(price);
        Console.Write("Subtotal: ${0}", subtotal);

    }
}

}

尝试对 Artem 的答案进行这种变体。 我认为这更清洁一些。

int count = 0;
decimal input = 0;
decimal price = 0;

while (true)
{
    Console.Write("Item {0} Enter Price: ", count++);
    input = Convert.ToDecimal(Console.ReadLine());
    if (input == -1)
    {
        break;
    }
    price += input;
}

使用列表并不断将条目添加到列表中。 或者您可以将运行总数保留为另一个整数。

就像是:

int total = 0; // declare this before your loop / logic other wise it will keep getting reset to 0.
total = total+ input;

在循环的每次迭代中,您都会覆盖price的值。 单独的输入和存储price

decimal input = 0;

do
{
    Console.Write("Item {0} Enter Price: ", count);
    ++count;
    input = Convert.ToDecimal(Console.ReadLine());
    if (input != -1)
        price += input;
} while (input != -1);

请尝试使用这个

using System;

namespace ConsoleApp1
{
class Program
{
    static void Main()
    {
        Console.WriteLine("Your Receipt");
        Console.WriteLine("");
        Console.WriteLine("");

        decimal count;
        decimal price;
        decimal subtotal = 0m; //subtotal is needed to be initialized from 0
        decimal tax;
        decimal total;

        count = 1;

        do
        {
            Console.Write("Item {0} Enter Price: ", count);
            ++count;
            price = Convert.ToDecimal(Console.ReadLine());
            if (price != -1)  //if the console input -1 then we dont want to make addition
              subtotal += price; 

        } while (price != -1);

        //subtotal = Convert.ToInt32(price); this line is needed to be deleted. Sorry I didnt see that.
        Console.Write("Subtotal: ${0}", subtotal); //now subtotal will print running total

    }
}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM