Visual Studio中口口声声说Use of unassigned variable的iVal和iNumber.谁能告诉我哪里出错了?
这是一个代码,要求用户继续输入整数并将其添加到用户想要停止.然后在控制台上显示整数之和.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AddFive
{
class Program
{
static void Main(string[] args)
{
int iNumber;
int iVal;
int iTotal = 0;
while (iVal > 0)
{
Console.WriteLine("Enter number " + iNumber);
iVal = Convert.ToInt32(Console.ReadLine());
iTotal = iTotal + iVal;
}
if (iNumber <= 0)
{
Console.WriteLine("Total = " + iTotal);
iVal = Convert.ToInt32(Console.ReadLine());
iTotal = iTotal + iVal;
}
Console.WriteLine("Total = " + iTotal);
Console.WriteLine();
Console.WriteLine("Press any key to close");
Console.ReadKey();
}
}
}
Run Code Online (Sandbox Code Playgroud)
为这些变量分配值.在使用它们之前,需要为局部变量赋值
int iNumber = 0;
int iVal = 0;
Run Code Online (Sandbox Code Playgroud)
当你写的时候while (iVal > 0),iVal没有设置值
您只能使用instance/class变量来逃避它,因为它们被初始化为默认值
public class Program
{
int i; //this was not implicitly initialized to zero (0)
public Program()
{
int j; //need to initialize this before use
Console.Write(j); //this throws "Use of unassigned variable" error
Console.Write(i); //this prints 0, the default value
}
}
Run Code Online (Sandbox Code Playgroud)
Visual Studio是正确的,您正在尝试引用未初始化的变量.
试试这个:
int iNumber = 0;
int iVal = 0;
Run Code Online (Sandbox Code Playgroud)
这样,您正在将变量初始化为初始值0.原始问题出现在这些行上:
while (iVal > 0)
和
if (iNumber <= 0)
在为变量赋值之前,您尝试访问变量.