2012-11-23 180 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

非常感谢你! –