[英]c# switch loop, adding up total for each case
我有2个代码想要合并为1个代码,这样做很麻烦。 该代码应先询问组号,然后再询问其捐赠金额,然后循环返回,直到按0。一旦按0,它将显示所有组的总数。 这是2个不同的代码
代码1
using System;
public class TotalPurchase
{
public static void Main()
{
double donation;
double total = 0;
string inputString;
const double QUIT = 0;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString = Console.ReadLine();
donation = Convert.ToDouble(inputString);
while(donation != QUIT)
{
total += donation;
Console.WriteLine("Enter next donation amount, or " +
QUIT + " to quit ");
inputString = Console.ReadLine();
donation = Convert.ToDouble(inputString);
}
Console.WriteLine("Your total is {0}", total.ToString("C"));
}
}
代码2
using System;
namespace donate
{
class donate
{
public static void Main()
{
begin:
string group;
int myint;
Console.WriteLine("Please enter group number (4, 5, or 6)");
Console.WriteLine("(0 to quit): ");
group = Console.ReadLine();
myint = Int32.Parse(group);
switch (myint)
{
case 0:
Console.WriteLine("Bye.");
break;
case 4:
case 5:
case 6:
double donation;
string inputString;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString = Console.ReadLine();
donation = Convert.ToDouble(inputString);
goto begin;
default:
Console.WriteLine("Incorrect grade number.", myint);
goto begin;
}
}
}
}
所以基本上我想使用第二代码找到每个组的总数。
任何帮助将不胜感激。
不要那样使用goto。 只需像在第一个代码段中那样使用另一个while循环即可。
这样说会更加简洁:
if (myInt > 3 && myInt < 7) { ... }
而不是使用该switch语句。
基本上,您用于汇总捐赠金额的代码可以解决问题,因此,只需将其放在处理组号的类似循环中即可。 如果这样做,您将要使用不同的输入来表示捐赠的结束与输入的结束。 如果应用程序说“输入0退出输入”,然后显示“输入0退出捐赠输入”,将造成混乱。
您与代码2非常接近。如果将代码2放入while循环中,它将起作用!
我在这里为您编写的唯一代码在while循环外声明为myint,并将其初始化为非零值。
double total = 0;
int myint = -1;
while (myint != 0)
{
string group;
Console.WriteLine("Please enter group number (4, 5, or 6)");
Console.WriteLine("(0 to quit): ");
group = Console.ReadLine();
myint = Int32.Parse(group);
switch (myint)
{
case 0:
Console.WriteLine("Bye.");
break;
case 4:
case 5:
case 6:
double donation;
string inputString;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString = Console.ReadLine();
donation = Convert.ToDouble(inputString);
total += donation;
break;
default:
Console.WriteLine("Incorrect grade number.", myint);
break;
}
}
Console.WriteLine("Your total is {0}", total.ToString("C"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.