[英]C# do while loops - How to remember user input?
I'm new to C#, and i'm writing a do while loop that continues to ask the user to enter "price", until they enter "-1" for price.我是 C# 新手,我正在编写一个 do while 循环,该循环继续要求用户输入“价格”,直到他们输入“-1”作为价格。
Afterwards, I need to add up all the values for price they entered and declare that as the subtotal.之后,我需要将他们输入的所有价格值相加,并将其声明为小计。
The problem I have is that it only remember the last number entered, which would be -1.我遇到的问题是它只记住最后输入的数字,即 -1。 What would I have to do to fix this?
我该怎么做才能解决这个问题?
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);
}
}
} }
Try this variation to Artem's answer.尝试对 Artem 的答案进行这种变体。 I think this is a little cleaner.
我认为这更清洁一些。
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;
}
Use a list and keep adding the entries to the list.使用列表并不断将条目添加到列表中。 Or you can keep a running total in another integer.
或者您可以将运行总数保留为另一个整数。
Something like:就像是:
int total = 0; // declare this before your loop / logic other wise it will keep getting reset to 0.
total = total+ input;
In each iteration of the loop, you overwrite the value of price
.在循环的每次迭代中,您都会覆盖
price
的值。 Separate input and storage 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);
Please try to use this请尝试使用这个
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.