我正在使用简化计算器,用户必须为两个操作添加2个或更多数字:
1.Addition
2.Subtraction
3.Multiplication
4.Division
但是每次我输入两个以上的数字时,它都无法正常工作。你能解释一下为什么吗?
private static void Main(string[] args)
{
switch (ChooseOperation())
{
case "1":
Addition();
break;
...
default:
break;
}
}
private static string ChooseOperation()
{
string choose = "Choose from 1 to 4 for operation: \n 1.Addition\n 2.Subtraction\n 3.Multiplication\n 4.Division";
string[] option = { "1", "2", "3", "4" };
Console.WriteLine(choose);
string operation = Console.ReadLine();
while (!option.Contains(operation))
{
Console.WriteLine("You have to enter right option!");
Console.WriteLine(choose);
operation = Console.ReadLine();
}
return operation;
}
private static int[] ChooseOperands()
{
int[] operands = new int[2];
Console.Write("Enter first operand: ");
operands[0] = int.Parse(Console.ReadLine());
Console.Write("Enter second operand: ");
operands[1] = int.Parse(Console.ReadLine());
return operands;
}
private static void Addition()
{
Console.WriteLine("You selected Addition (+)");
int[] operands = ChooseOperands();
int result = 0;
for (int index = 1; index < operands.Length; index++)
result += operands[index];
Console.WriteLine();
Console.WriteLine("Addition result: {0}", result);
Console.ReadKey();
}
请注意,Substraction,Multiplication和Division与Addition非常相似
答案 0 :(得分:1)
尝试在ChooseOperands方法中添加参数。
private static int[] ChooseOperands(int n)
{
int[] operands = new int[n];
Console.Write("Enter first operand: ");
operands[0] = int.Parse(Console.ReadLine());
Console.Write("Enter second operand: ");
operands[1] = int.Parse(Console.ReadLine());
return operands;
}