我刚开始学习循环,我不明白如何使用for
或while
语句在输出中累积多个总数。
我的代码是代表三个家庭(A,B和C)有车库出售。当他们输入姓名缩写时,他们可以输入一笔销售金额。他们可以根据需要添加任意数量的金额,当他们想看到他们的总数时,他们按 Z 它将显示每个家庭的总数,以及在车库出售时的总额。 / p>
我无法弄清楚如何显示所有总数。我应该怎么做呢?
这是我到目前为止所做的:
static void Main(string[] args)
{
double totalFamilyA;
double totalFamilyB;
double totalFamilyC;
double grandTotal = 0;
double saleAmount;
string familyInitial;
string inputSale;
Console.Write("Enter your family initial A, B, or C (uppercase/lowercase accepted) ");
familyInitial = Console.ReadLine();
Console.Write("Enter sale amount $");
inputSale = Console.ReadLine();
saleAmount = Convert.ToDouble(inputSale);
while (familyInitial != "Z" && familyInitial != "z")
{
totalFamilyA = Convert.ToDouble(inputSale);
totalFamilyB = Convert.ToDouble(inputSale);
totalFamilyC = Convert.ToDouble(inputSale);
if (familyInitial == "A" || familyInitial == "a")
{
totalFamilyA += saleAmount;
Console.Write("Enter next sale amount or press 'Z' or 'z' to see the grand total $");
inputSale = Console.ReadLine();
saleAmount = Convert.ToDouble(inputSale);
totalFamilyA = Convert.ToDouble(saleAmount);
}
else if (familyInitial == "B" || familyInitial == "b")
{
totalFamilyB += saleAmount;
Console.Write("Enter next sale amount or press 'Z' or 'z' to see the grand total $");
inputSale = Console.ReadLine();
saleAmount = Convert.ToDouble(inputSale);
totalFamilyB = Convert.ToDouble(saleAmount);
}
else if (familyInitial == "C" || familyInitial == "c")
{
totalFamilyC += saleAmount;
Console.Write("Enter next sale amount or press 'Z' or 'z' to see the grand total $");
inputSale = Console.ReadLine();
saleAmount = Convert.ToDouble(inputSale);
totalFamilyC = Convert.ToDouble(saleAmount);
}
}
Console.WriteLine("Your total is {0}", grandTotal.ToString("C"));
}
答案 0 :(得分:1)
听起来你想要这样的东西:
int familyACount = 0;
int familBCount = 0;
int familyCCount = 0;
while(_inputString.toLower()!="z")
{
//Parse input text here to work out the initials and amount entered
string initials = //Something
int amount = //Something
if(initials == familyAInitials) familyACount += amount;
//Repeat for other two families
}
//Z has been entered, so output the totals
Debug.Print("Family A:"+familyACount);
//Repeat for other families
Debug.Print("Total:" + (familyACount + familyBCount + familyCCount));
你会想要找出在输入结束时获取值的最佳方法(我假设首字母和总数输入为一个字符串)并且你可能想要在整数中加倍,因为你正在处理有钱。
如果您也想要添加金额,也可以输出运行总计,如果输入文本不是一组首字母等,也可以输出提示“Z退出”。
祝你好运!答案 1 :(得分:1)
你不需要循环语句 你可以简单地写下以下几行来实现你的目标
public enum PersonIntial
{
Person1,
Person2,
Person3,
All
}
public int Person1Acnt { get; set; }
public int Person2Acnt { get; set; }
public int Person3Acnt { get; set; }
public int TotalSales { get; set; }
private void ProcessInput(PersonIntial pInitail, int amount)
{
switch (pInitail)
{
case PersonIntial.Person1:
{
Person1Acnt += amount;
}
break;
case PersonIntial.All:
{
TotalSales = Person1Acnt + Person2Acnt + Person3Acnt;
}
break;
}
}
将您的输入转换为枚举....... 并调用ProcessInput()
由于