我是 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
}