错误1名称在当前上下文中不存在

本文关键字:上下文 不存在 1名 错误 | 更新日期: 2023-09-27 18:15:42

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();
    }
}

的问题是,当我试图运行程序时,它说名称:

'avg'在当前上下文中不存在

为什么会发生这种情况,我该如何解决它

错误1名称在当前上下文中不存在

在循环的作用域中定义avg,因此它不存在于作用域之外。(当您将新值分配给avg时,不要替换现有值,而是使用+=来增加现有值)

修复:

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

另外,请记住在打印平均值时将其除以添加的项目数:(请记住将其中一个操作数转换为保存小数点的类型,而不是int -因此您将得到真正的平均值,而不是它的四舍五入int版本)

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

请参阅MSDN中的作用域,以了解何时何地可以访问变量和方法。

在"while"的作用域中声明了"avg"变量。

你应该在while语句外声明avg变量

如果在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();
          }
     }

类似这样,参见注释:

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();