我在C#上遇到编译器错误,您能帮我吗?

发布于 2025-02-04 17:49:45 字数 421 浏览 3 评论 0原文

我遇到了一个错误,您可以帮助我

视觉工作室说印刷部分中的H存在问题:

错误CS0165:使用未分配的本地变量'H'(CS0165)

static void Main()
{
    int[ , ] m = new int [8,8];
    int i ;
    int h ;
    Random rnd = new Random();
    for( i = 0 ; i< 8 ; i++)
    {
        for( h = 0 ; h< 8 ; h++)
        {
            m[i,h] = rnd.Next(10);
        }
    }
    Console.WriteLine(m[i,h]);
      
}

I am getting an error can you help me

Visual Studio says there is a problem with the h in the print part:

Error CS0165: Use of unassigned local variable 'h' (CS0165)

static void Main()
{
    int[ , ] m = new int [8,8];
    int i ;
    int h ;
    Random rnd = new Random();
    for( i = 0 ; i< 8 ; i++)
    {
        for( h = 0 ; h< 8 ; h++)
        {
            m[i,h] = rnd.Next(10);
        }
    }
    Console.WriteLine(m[i,h]);
      
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

探春 2025-02-11 17:49:45

您的变量没有分配的值:

int i ;
int h ;

现在,编译器知道i 将在此处分配一个值:

for( i = 0 ; i< 8 ; i++)

在hood下方没有太深的情况下,基本上是i = 0无论循环机构是否执行,都可以保证发生零件。然后我们知道h也将在此处分配一个值:

for( h = 0 ; h< 8 ; h++)

因为我们知道外循环至少执行一次,因为我们知道0小于8。但是编译器并不意识到这一点。编译器遵循一组简单的规则,以保证它的保证。这些规则不包括执行程序的逻辑以查看是否会发生任何事情。

因此,最重要的是,虽然编译器 can 保证i将分配一个值,但它不能保证h会。因此错误。

简单的解决方案只是将值分配给您的变量:

int i = 0;
int h = 0;

Your variables have no assigned values:

int i ;
int h ;

Now, the compiler knows that i will be assigned a value here:

for( i = 0 ; i< 8 ; i++)

Without looking too deep under the hood, basically the i = 0 part is guaranteed to happen whether the loop body executes or not. Then we know that h will also be assigned a value here:

for( h = 0 ; h< 8 ; h++)

Because we know that the outer loop will execute at least once, because we know 0 is less than 8. But the compiler isn't as aware of this. The compiler follows a simpler set of rules for the guarantees that it makes. And those rules do not include executing the program's logic to see if something will or won't happen.

So the bottom line is that, while the compiler can guarantee that i will be assigned a value, it can not guarantee that h will. Hence the error.

The simple solution is just to assign values to your variables:

int i = 0;
int h = 0;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文