2012-11-23 206 views
0

我有這樣的代碼:while循環在C#

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace _121119_zionAVGfilter_Nave 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      int cnt = 0, zion, sum = 0; 
      double avg; 
      Console.Write("Enter first zion \n"); 
      zion = int.Parse(Console.ReadLine()); 
      while (zion != -1) 
      { 
       while (zion < -1 || zion > 100) 
      { 
       Console.Write("zion can be between 0 to 100 only! \nyou can rewrite the zion here, or Press -1 to see the avg\n"); 
       zion = int.Parse(Console.ReadLine()); 
      } 

       cnt++; 
       sum = sum + zion; 
       Console.Write("Enter next zion, if you want to exit tap -1 \n"); 
       zion = int.Parse(Console.ReadLine()); 


      } 
      if (cnt == 0) 
      { 
       Console.WriteLine("something doesn't make sence"); 
      } 
      else 
      { 
       avg = (double)sum/cnt; 
       Console.Write("the AVG is {0}", avg); 

      } 
     Console.ReadLine(); } 
    } 
} 

這裏的問題是,如果在開始的時候我進入一個負數或百餘數量大,我會得到這個消息:「錫安可在0僅限100!\ n您可以在此重寫zion,或按-1查看avg \ n「。
如果我再參加-1,則顯示出來代替AVG:「輸入下一個zion,如果要退出 ,請敲擊-1 \ n。」
我該如何解決這個問題,因此當數字爲負數或大於數百且小於-1時,我會看到AVG不是另一條消息?

回答

1

你可以只添加一個標誌變量被執行,它的完成。

namespace _121119_zionAVGfilter 
{ 
    class Program 
    { 
     static void Main(string[] args) 
    { 
     int cnt = 0, zion, sum = 0; 
     double avg; 
     int flag = 0; 
     Console.Write("Enter first zion \n"); 
     zion = int.Parse(Console.ReadLine()); 
     while (zion != -1) 
     {     
      while (zion < -1 || zion > 100) 
      { 
       Console.Write("zion can be between 0 to 100 only! \nyou can rewrite the zion here, or Press -1 to see the avg\n"); 
       zion = int.Parse(Console.ReadLine()); 
       if(zion== -1) 
        flag = 1; 
      }     
      cnt++; 
      sum = sum + zion; 
      if (flag == 1) 
       break; 
      Console.Write("Enter next zion, if you want to exit tap -1 \n"); 
      zion = int.Parse(Console.ReadLine()); 
      if (cnt != 0) { } 

     } 
     if (cnt == 0) 
     { 
      Console.WriteLine("something doesn't make sence"); 
     } 
     else 
     { 
      avg = (double)sum/cnt; 
      Console.Write("the AVG is {0}", avg);     
     }    
     Console.ReadLine(); 
     } 
    } 
} 
+0

謝謝!有用! –

+0

歡迎,不要提及:) –

+0

嘿,你可以解決這個問題,而無需添加其他變量? –

1

只需附上這個代碼,你不想在if聲明中這樣

if(zion != -1) 
{ 
     cnt++; 
     sum = sum + zion; 
     Console.Write("Enter next zion, if you want to exit tap -1 \n"); 
     zion = int.Parse(Console.ReadLine()); 
     if (cnt != 0){} 
} 
+0

非常感謝你! –