-1

Hello I am practicing with C$ specifically with decimal numeric values. I have this simple program just to check if the inputted data is correct. I input 12.9 but get 49. Any help would be appreciated.

static void Main(string[] args)
        {
            Console.Write("Enter the first number 1: ");
            double num1 = Console.Read();
            Console.Write(num1);
            //Console.WriteLine(num1+" + "+num2+" + "+num3 + " = "+total);
        }
Joe Kennedy
  • 83
  • 1
  • 5
  • [Console.Read](https://learn.microsoft.com/en-us/dotnet/api/system.console.read?view=net-5.0) doesn't do what you think. It returns the character code of the key pressed ( '1' = Ascii 49). You need to use Console.ReadLine and then parse the input converting it to a double – Steve Sep 04 '21 at 17:50

1 Answers1

1

You need to use Console.ReadLine() and not Console.Read().

Read method - Reads the next character from the standard input stream.

ReadLine method - Reads the next line of characters from the standard input stream.

Try this:

static void Main(string[] args)
{
    Console.Write("Enter the first number 1: ");

    // It might cause an error if the user doesn't write a number 
    // which is parsable to double
    double num1 = double.Parse(Console.ReadLine());
    Console.Write(num1);
}

Or a safe way:

static void Main(string[] args)
{
    Console.Write("Enter the first number 1: ");

    // You may also ask the user to write again an input of number.
    if (double.TryParse(Console.ReadLine(), out double num1))
    {
        Console.Write(num1);
    }
}

Misha Zaslavsky
  • 8,414
  • 11
  • 70
  • 116
  • Not to be picky here but really you shouldn't teach to use Parse on a user input value. – Steve Sep 04 '21 at 17:55