为什么2会自动转换为299?

时间:2011-03-26 00:25:34

标签: c# windows

我是新人:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        private static void Main()
        {
            Console.WriteLine("Welcome to my calculator");
            Console.WriteLine("Calculator only supports -,+,/,*");
            Console.WriteLine("Calculator V1.20 alpha");

            Console.WriteLine("Enter your first number");
            int num1 = Console.ReadKey().KeyChar;
            Console.WriteLine("Enter your operator");
            Console.WriteLine();
            char operation = Console.ReadKey().KeyChar;
            Console.WriteLine("Enter your second number");
            Console.WriteLine();
            int num2 = Console.ReadKey().KeyChar;
            //the answer variables
            int answersubtract = num1 - num2;
            int answeradd = num1 + num2;
            int answermulti = num1 * num2;
            int answerdiv = num1 / num2;


            if (operation == '-')
            {
                Console.WriteLine(answersubtract);
            }

            else if (operation == '+')
            {
                Console.WriteLine(answeradd);
            }
            else
            {
                if (operation == '*')
                {
                    Console.WriteLine(answermulti);
                }

                else
                {
                    if (operation == '/')
                    {
                        Console.WriteLine(answerdiv);

                    }
                }
            }

            Console.ReadKey();
        }
    }
}

修改

我发送给该程序的输入是:

  

1 + 2

2 个答案:

答案 0 :(得分:3)

 int num1 = Console.ReadKey().KeyChar;

您正在阅读一个角色,而不是一个数字。查看ConsoleKeyInfo.KeyChar的文档。

允许用户输入实数:

 int num1 = int.Parse(Console.ReadLine());

专注于程序版本2中的错误处理和开关语句。

答案 1 :(得分:0)

因为当您输入2时,表示为char,其值为229