从 Do-While 函数获取值

Getting a value from a Do-While function

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

我需要能够存储每次迭代的“价格”。但是如果不覆盖我的价值观,我就无法做到这一点。我是 C# 的新手,不太确定该怎么做。

试试这个

List<decimal> prices  = new List<decimal>();

decimal price=0;
int count=0;

        do
        {
            count++;
            Console.WriteLine("Item {0}", count);
            Console.WriteLine("     Enter Price: $ ");
            price = Convert.ToDecimal(Console.ReadLine());
            prices.Add(price);
       
        } while ( price != -1);

Console.WriteLine ("Price history:");

foreach(var item in prices)
{
        Console.WriteLine(item.ToString());
}

我会将您的价格存储在字典中,以确保不会添加相同商品的价格。这是一个带有示例的 fiddle:https://dotnetfiddle.net/uZQqDp

public static void Main()
{
    Dictionary<int, decimal> prices = new Dictionary<int, decimal>();

    int count = 0;
    bool finished = false;
    do
    {
        Console.Write("Item {0}:\tEnter Price: $", count);

        var price = Console.ReadLine();
        var convertedPrice = Convert.ToDecimal(price);
        
        if(convertedPrice != -1)
        {
            prices.Add(count, convertedPrice);
            count++;
        }
        else
        {
            finished = true;
        }
    } while(!finished);
    
    Console.WriteLine("Price History");
    foreach(var price in prices)
    {
        Console.WriteLine("Item {0}:\tPrice: ", price.Key, price.Value);
    }
}