2016-10-31 36 views
-2
class Program 
{ 
    static void Main(string[] args) 
    { 
     int f = 0; 
     Console.WriteLine("enter ammount of tries"); 
     int trycount = Convert.ToInt32(Console.ReadLine()); 
     Random numgen = new Random(); 
     while (f < trycount) 
     { 
      int now = numgen.Next(1, 6); 
      int avg = 0 + now; 
      f++; 
     } 
     Console.WriteLine(avg); 
     Console.ReadLine(); 
    } 
} 

問題是存在的,這個名字:錯誤當我嘗試運行它說,這個項目的名稱不會在目前情況下

「平均」不在當前情況下存在

爲什麼會發生這種情況,我該如何解決這個問題。

+1

定義平均超出了你的循環範圍。 – mybirthname

回答

1

您正在定義循環範圍內的avg,因此它不在範圍之外。 (也當您在新的值賦給avg不替換現有的值,但使用+=增加現有值)

修復:

int avg = 0; 
while (f < trycount) 
{ 
    int now = numgen.Next(1, 6); 
    avg += now; 
    f++; 
} 

另外記得打印的平均分才當通過添加的項目數量:(記得將其中一個操作數轉換爲保存小數點的類型,而不是int - 因此您將獲得實際的平均值,而不是它的舍入版本)

Console.WriteLine(avg/(double)f); 

請參考MSDN中的作用域以瞭解更多變量和方法在何時何地被訪問。

0

您在「while」的範圍內聲明瞭「avg」變量。超出範圍的任何內容都無法看到變量。

你應該在while之外聲明你的avg變量。

0

如果在while循環中聲明變量,它會拋出一個錯誤,因爲「名稱」avg「在當前上下文中不能存在」。因爲你可以在while循環中聲明,當while循環中的條件不能滿足時,變量不能定義並在打印結果時聲明,所以它會拋出一個錯誤。

所以我們可以在while循環之外定義變量。

class Program 
    { 
     static void Main(string[] args) 
     { 
      int f = 0,avg=0; 
      Console.WriteLine("enter ammount of tries"); 
      int trycount = Convert.ToInt32(Console.ReadLine()); 
      Random numgen = new Random(); 
      while (f < trycount) 
      { 
       int now = numgen.Next(1, 6); 
       avg = 0 + now; 
       f++; 
      } 
      Console.WriteLine(avg); 
      Console.ReadLine(); 
      } 
    } 
0

這樣的事情,看評論:

class Program 
{ 
    static void Main(string[] args) 
    { 
     Console.WriteLine("enter amount of tries"); // typo 
     int TryCount = Convert.ToInt32(Console.ReadLine()); 

     Random numgen = new Random(); 

     // it is sum we compute in the loop (add up values), not average 
     // double: final average will be double: say 2 tries 4 and 5 -> 4.5 avg 
     // please notice, that sum is declared out of the loop's scope 
     double sum = 0.0; 

     // for loop looks much more natural in the context then while one 
     for (int i = 0; i < TryCount; ++i) 
      sum += numgen.Next(1, 6); 

     // we want to compute the average, right? i.e. sum/TryCount 
     Console.WriteLine(sum/TryCount); 
     Console.ReadLine(); 
    } 
} 

僅供參考:在現實生活中,我們通常使用的LINQ這是更緊湊,可讀

Console.WriteLine("enter amount of tries"); // typo 
int TryCount = Convert.ToInt32(Console.ReadLine()); 

Random numgen = new Random(); 

Console.Write(Enumerable 
    .Range(0, TryCount) 
    .Average(x => numgen.Next(1, 6))); 

Console.ReadLine(); 
相關問題