Home > Software engineering >  C# double value displaying incorrect value [duplicate]
C# double value displaying incorrect value [duplicate]

Time:09-17

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

CodePudding user response:

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

  • Related