-2

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

使用未分配的局部变量“总计”

局部变量“total”在访问之前可能未初始化

这是代码:

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
}
4

3 回答 3

1

问题:如果op是会发生什么^

答:total从来没有分配到。这是 C# 中的错误。

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

int total = 0;
于 2018-10-30T19:16:28.437 回答
0

我建议使用 Nullable 整数以分配给它的 null 值开始,最后检查它是否具有值以确定用户是否输入了适当的运算符。

int? total = null;
于 2018-10-30T19:42:31.343 回答
0

正如 Blindy 所说,您需要使用变量 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;
    default:
        throw new OperatorUnknownException(op);
}

如您所见,当操作员未知时会引发异常。然后你需要在调用函数中处理这种类型的异常。

于 2018-10-30T19:51:08.943 回答