我是C#的新手,我正在编写一个do while循环,继续要求用户输入" price",直到他们输入" -1&# 34;价格。
之后,我需要将他们输入的价格的所有值相加,并将其作为小计。
我遇到的问题是它只记得输入的最后一个数字,即-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);
}
}
}
答案 0 :(得分:2)
尝试这种变化来回应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;
}
答案 1 :(得分:1)
使用列表并继续将条目添加到列表中。 或者您可以将运行总计保持为另一个整数。
类似的东西:
int total = 0; // declare this before your loop / logic other wise it will keep getting reset to 0.
total = total+ input;
答案 2 :(得分:1)
在循环的每次迭代中,您都会覆盖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);
答案 3 :(得分:-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
}
}
}