[英]I get Compiler Error on C# Can you help me?
I am getting an error can you help me我收到一个错误你能帮我吗
Visual Studio says there is a problem with the h in the print part: Visual Studio 说打印部分的 h 有问题:
Error CS0165: Use of unassigned local variable 'h' (CS0165)
错误 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]);
}
Your variables have no assigned values:您的变量没有赋值:
int i ;
int h ;
Now, the compiler knows that i
will be assigned a value here:现在,编译器知道
i
将在这里被赋值:
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.无需在引擎盖下看得太深,基本上
i = 0
部分无论循环体是否执行都会保证发生。 Then we know that h
will also be assigned a value here:那么我们知道这里也会给
h
赋值:
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.因为我们知道外循环至少会执行一次,因为我们知道 0 小于 8。但是编译器并没有意识到这一点。 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.所以底线是,虽然编译器可以保证
i
将被分配一个值,但它不能保证h
会。 Hence the error.因此错误。
The simple solution is just to assign values to your variables:简单的解决方案就是为变量赋值:
int i = 0;
int h = 0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.