开发者

why 2 is automatically converted to 299?

开发者 https://www.devze.com 2023-02-19 16:24 出处:网络
I\'m new: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1

I'm new:

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.Write开发者_高级运维Line(answeradd);
            }
            else
            {
                if (operation == '*')
                {
                    Console.WriteLine(answermulti);
                }

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

                    }
                }
            }

            Console.ReadKey();
        }
    }
}

Edit:

The input I am sending to the program is:

1+2


 int num1 = Console.ReadKey().KeyChar;

You are reading a character, not a number. Review the docs for ConsoleKeyInfo.KeyChar.

Allow the user to enter real numbers:

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

Focus on error handling and the switch statement in version 2 of your program.


Because when you enter 2 its represented as a char which its value is 229.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号