Visual Studio抛出错误“使用未赋值的变量”
本文关键字:赋值 变量 Studio 出错 错误 Visual | 更新日期: 2023-09-27 17:50:35
好的,我给编程课布置了一个作业,用不同操作的方法创建一个计算器。在这一行:
Console.WriteLine("{0}{1}{2}", num1, op, num2);
我接收错误2使用未赋值的局部变量'op'
我不知道为什么,这里是整个代码:提前感谢您的帮助。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LabAssignFiveCalc
{
class Program
{
//Addition method
static double Addition(int num1, int num2)
{
double result;
result = num1 + num2;
return result;
}
//Subtraction method
static double Subtract(int num1, int num2)
{
double result;
result = num1 - num2;
return result;
}
//Multiplication method
static double Multiply(int num1, int num2)
{
double result;
result = num1 * num2;
return result;
}
//Division method
static double Divide(int num1, int num2)
{
double result;
result = num1 / num2;
return result;
}
//Main
static void Main(string[] args)
{
//Declare Variables
int choice;
string op;
double num1;
double num2;
double result;
//Ask user for calculation parameters
Console.WriteLine("Calculator:");
Console.WriteLine("Which operation do you wish to perform? Type the corresponding number.");
Console.WriteLine("1) Addition'n2) Subration'n3) Multiplication'n4) Division");
choice = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please type the first number you wish to calculate");
num1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Please type the second number you wish to calculate");
num2 = Convert.ToDouble(Console.ReadLine());
//Declare Operator
switch (choice)
{
case 1:
op = "+";
break;
case 2:
op = "-";
break;
case 3:
op = "*";
break;
case 4:
op = "/";
break;
}
//Show Calculation
Console.WriteLine("{0}{1}{2}", num1, op, num2);
Console.ReadKey();
}
}
}
你没有default
选项在switch
块,所以op
变量可以不分配,如果用户将输入其他的1,2,3或4
我建议你使用循环来再次询问用户是否输入了无效的值:
int choice;
do
{
Console.WriteLine("1)Addition'n2)Subration'n3)Multiplication'n4)Division");
choice = Convert.ToInt32(Console.ReadLine());
}
while (choice < 1 && 4 < choice);
下一个是添加默认大小写:
switch (choice)
{
case 1: op = "+"; break;
case 2: op = "-"; break;
case 3: op = "*"; break;
case 4: op = "/"; break;
default:
throw new InvalidOperationException();
}
或者,您可以将所有非1、2或3的值视为除法运算:
switch (choice)
{
case 1: op = "+"; break;
case 2: op = "-"; break;
case 3: op = "*"; break;
default:
op = "/"; break;
}
可以在声明变量时指定默认值,而不是添加默认大小写:
string op = null;
规则:你应该总是初始化你所有的局部变量。
如果你观察你的代码num1
和num2
在开关块之前被正确初始化,但是你在switch
块中分配op
值。
编译器在你运行程序之前不能确定哪个块被执行。
因此,您应该在switch块之前初始化op
,或者您应该声明默认块以确保在编译时初始化。
解决方案1:
替换:
string op;
与这个:
string op = string.Empty;
解决方案2:
switch (choice)
{
case 1:
op = "+";
break;
case 2:
op = "-";
break;
case 3:
op = "*";
break;
case 4:
op = "/";
break;
default:
op = "";
break;
}