class Program
{
static void Main(string[] args)
{
bool run = true;
do
{
Console.WriteLine("Make a choice or type 0 to exit: ");
Console.WriteLine("1. Add 2 numbers\n2. Subtract 2 numbers\n3.Multiply 2 numbers\n4. Divide 2 numbers");
int choice = Convert.ToInt32(Console.ReadLine());
if (choice == 0)
{
run = false;
}
if(choice == 1)
{
int x, y;
Console.Write("Enter 2 numbers to Operate on: ");
x = Convert.ToInt32(Console.Read());
y = Convert.ToInt32(Console.Read());
Console.WriteLine("The Result is: {0}", Convert.ToInt32(add(x,y)));
}
}while(run);
Console.ReadKey();
}
public static int add(int x, int y)
{
return x+y;
}
public static int sub(int x, int y)
{
return x - y;
}
public static int mult(int x, int y)
{
return x * y;
}
public static double div(int x, int y)
{
return (float)x / y;
}
我对C#相当陌生,因此对于补救性问题深表歉意。
问题是,当我运行并输入1并输入2和4时,我得到82,然后菜单被打印两次。这显然是不正确的。有人可以告诉我为什么会这样吗?我认为这与我进行转换的原因有关,但是我想确定知道为什么该语言表现得像它一样,因为这似乎应该起作用。感谢您的帮助。
编辑:我不确定为什么我被低票,请让我知道我做错了什么...
这是一个示例输出:
Make a choice or type 0 to exit:
1. Add 2 numbers
2. Subtract 2 numbers
3. Multiply 2 numbers
4. Divide 2 numbers
1
Enter 2 numbers to Operate on: 2 4
The Result is: 82
Make a choice or type 0 to exit:
1. Add 2 numbers
2. Subtract 2 numbers
3. Multiply 2 numbers
4. Divide 2 numbers
Make a choice or type 0 to exit:
1. Add 2 numbers
2. Subtract 2 numbers
3. Multiply 2 numbers
4. Divide 2 numbers
最佳答案
问题出在这里:
x = Convert.ToInt32(Console.Read());
y = Convert.ToInt32(Console.Read());
您不应该在这里使用
Read
。 Read
读取单个字符并将其转换为相应的ASCII值。基本上,您要一起添加ASCII值。解决方案:
您只需将其更改为
ReadLine
:x = Convert.ToInt32(Console.ReadLine());
y = Convert.ToInt32(Console.ReadLine());
但是,如果您希望两个数字之间用空格分隔,例如
2 4
,则可以执行以下操作:string[] numbers = Console.ReadLine().Split(' ');
x = Convert.ToInt32(numbers[0]);
y = Convert.ToInt32(numbers[1]);
关于c# - 试图用C#制作计算器。这是怎么了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42409629/