日期:2014-05-18  浏览次数:21048 次

while循环问题
class average
{
  public static void Main()
  {
  int ttl = 0; //variable to store the running total
  int nbr = 0; //variable for individual numbers
  int ctr = 0; //counter

  System.Random rnd = new System.Random(); //random number

  while (ctr < 10)
  { 
  //Get random number
  nbr = (int)rnd.Next(1, 11);
  System.Console.WriteLine("Number {0} is {1}",(ctr+1),nbr);
  ttl += nbr; //add nbr to total
  ctr++; //increment counter
  }
  System.Console.WriteLine("\nThe total of the {0} numbers is {1}", ctr, ttl);
  System.Console.WriteLine("\nTHe average of the numbers is {0}",ttl/ctr);
  }
}

当时ctr=0,条件满足循环,到System.Console.WriteLine("Number {0} is {1}",(ctr+1),nbr);ctr=1了,循环到ctr++; 时 ,ctr=2,条件满足,继续循环,到System.Console.WriteLine("Number {0} is {1}",(ctr+1),nbr)时,运行打印出:Number 2 is 4;
为什么(ctr+1)会是“2”?不是在第一次循环时,循环到ctr++时,ctr=2了吗??这样满足的话,到(ctr+1)不是“3”吗??
不明白哩~~~

------解决方案--------------------
第一次循环
ctr = 0
bbr = 5
System.Console.WriteLine("Number {0} is {1}",(ctr+1),nbr); 输出Number 1 is 5
ttl = 5 
ctr++ 后= 1第二次循环

ctr = 1
bbr = 4
System.Console.WriteLine("Number {0} is {1}",(ctr+1),nbr); 输出Number 2 is 4
ttl = 9 
ctr++ 后 = 2

ctr = 2
bbr = 1
System.Console.WriteLine("Number {0} is {1}",(ctr+1),nbr); 输出Number 3 is 1
ttl = 10 
ctr++ 后 = 3



搂主看错了循环