我正在试图弄清楚为什么我不能让我的方程式不能返回零,因为似乎由于某种原因,MathOperations方法没有做到这一点?如果有人可以提供帮助,我会非常感激。提前谢谢!
class MathUI
{
public void PromptForInt()
{
MathOperations ops = new MathOperations();
Console.WriteLine("Enter first number to calculate");
ops.Operand1 = int.Parse(Console.ReadLine());
Console.WriteLine("\nEnter second number to calculate");
ops.Operand2 = int.Parse(Console.ReadLine());
return;
}
public void PromptForChoice()
{
int choice;
MathOperations result = new MathOperations();
Console.WriteLine("\nWhat type of operation would you like to perform?");
Console.WriteLine("[1] Add \n[2] Subtract \n[3] Multiply \n[4] Divide \n[5] Exit \n");
Console.Write("Enter your choice: ");
choice = int.Parse(Console.ReadLine());
if (choice == 1)
{
Console.WriteLine(result.AddNumbers());
}
else if (choice == 2)
{
Console.WriteLine(result.SubtractNumbers());
}
else if (choice == 3)
{
Console.WriteLine(result.MultiplyNumbers());
}
else if (choice == 4)
{
Console.WriteLine(result.DivideNumbers());
}
else if (choice == 5)
{
Environment.Exit(0);
}
else
{
Console.WriteLine("\nInvalid input entered!");
}
}
class MathOperations
{
private int operand1;
private int operand2;
public int Operand1
{
get
{
return operand1;
}
set
{
operand1 = value;
}
}
public int Operand2
{
get
{
return operand2;
}
set
{
operand2 = value;
}
}
public MathOperations()
{
operand1 = 0;
operand2 = 0;
}
public int AddNumbers()
{
return operand1 + operand2;
}
public int SubtractNumbers()
{
return operand1 - operand2;
}
public float DivideNumbers()
{
return (float)operand1 / (float)operand2; // (float) used to show output with decimal point
}
public int MultiplyNumbers()
{
return operand1 * operand2;
}
答案 0 :(得分:3)
您正在为ops对象而不是结果对象设置operand1和operand2的值。
MathOperations ops = new MathOperations();
Console.WriteLine("Enter first number to calculate");
ops.Operand1 = int.Parse(Console.ReadLine());
Console.WriteLine("\nEnter second number to calculate");
ops.Operand2 = int.Parse(Console.ReadLine());
但是调用结果对象上的方法,其operand1和operand2初始化为0,因此函数的返回值。记得操作' operand1和operand2保持用户的输入,而不是结果的operand1和operand2。您应该使用相同的ops对象进行结果计算。