局部变量未在 WriteLine 中定义

local variable isn't defined in WriteLine

我是 c# 的新手,我正在尝试做一个简单的计算器。 但是,当我写 Console.WriteLine(total) 时,出现编译时错误:

Use of unassigned local variable 'total'

Local variable 'total' might not be initialized before accessing

代码如下:

static void Main(string[] args)
{        
    Console.WriteLine("write a number:");
    int num_one = Convert.ToInt32(Console.ReadLine());

    Console.WriteLine("write a operator: + ; - ; * ; /");
    string op = Console.ReadLine();

    Console.WriteLine("write a second number:");
    int num_two = Convert.ToInt32(Console.ReadLine());

    int total;

    switch (op)
    {
        case "+":
            total = num_one + num_two;
            break;
        case "-":
            total = num_one - num_two;
            break;
        case "*":
            total = num_one * num_two;
            break;
        case "/":
            total = num_one / num_two;
            break;
    }

    Console.WriteLine(total); // <-- this line gives a compile-time error
}

问题:如果 op^ 会怎样?

答案:total 从未分配给。这是 C# 中的错误。

要解决此问题,要么处理 switch 语句中的其他情况(应该很容易,只有几十万个情况),要么在声明时初始化 total 变量:

int total = 0;

我建议使用 Nullable integer 开始,并为其分配空值,最后检查它是否具有值,以确定用户是否输入了适当的运算符。

int? total = null;

正如 Blindy 所说,您需要使用变量总计的初始值或开关中的默认值来处理此问题。

但在此之前,您确实需要考虑当您尝试在两个数字之间进行未知运算时的逻辑场景是什么。

我最简单的解决方案如下所示:

switch (op)
{
    case "+":
        total = num_one + num_two;
        break;
    case "-":
        total = num_one - num_two;
        break;
    case "*":
        total = num_one * num_two;
        break;
    case "/":
        total = num_one / num_two;
        break;
    default:
        throw new OperatorUnknownException(op);
}

如您所见,当运算符未知时会抛出异常。那么你需要在调用函数中处理这种类型的异常。