c# - 试图用C#制作计算器。这是怎么了?

标签 c# error-handling calculator

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());

您不应该在这里使用ReadRead读取单个字符并将其转换为相应的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/

相关文章:

javascript - 如何将平方根添加到我的 JavaScript/HTML 计算器中?

c# - Visual Studio 2015 方法信息

MySQL - 适用于 AWS RDS 和 RR 支持的最佳内部错误处理技术

C++ 计算器没有像我想象的那样工作

excel - 虽然函数在错误处理程序中不起作用-VBA?

php - 如何使用FluentPDO检测错误

java - 我的 BMI 计算器出了什么问题?

c# - C#中变量类型的多态性

c# - 函数的返回值存储在哪里

c# - 为什么我在尝试将公共(public)方法的默认值设置为颜色时收到错误消息?