簡體   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