2011-03-26 78 views
0

我有,我想结合成1时遇到了很大的麻烦做2码。代码应该询问组号,然后请求他们的捐赠金额并循环,直到他们按0。一旦他们按0,它应该显示所有组的总数。这里有2个不同的代码C#切换回路,加起来总共为每个个案

码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; 
       } 




     }  
    } 
} 

所以基本上我想找到的总使用第二个代码每个组。

任何帮助将不胜感激。

+0

这是对一些说明学校的项目? – 2011-03-26 19:05:31

回答

0

不要使用那样的goto。只需使用另一个while循环,就像您在第一个代码段中所做的那样。

这将是更简洁地说:

if (myInt > 3 && myInt < 7) { ... } 

,而不是使用switch语句。

基本上你的总结捐赠金额代码的伎俩,所以才坚持一个类似的循环处理该组数字是什么里面。如果你这样做,你会想要使用不同的输入来表示捐赠结束与输入结束。如果应用程序显示“输入0以退出输入”,然后输入“0以退出捐赠输入”,将会引起混淆。

0

如果你把代码2的内部,而循环它的作品你都非常接近编码2!

我为你在这里写的唯一的代码被宣布while循环外敏,并将其初始化为非零值。

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"));