2011-03-26 83 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"));