-1

I just started to learn C# and I faced this problem: The Code:

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

namespace Test_CSharp_
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the number: ");
            double num = Console.Read();
            
            Console.WriteLine("Result = " + num*num);
            
        }        
        
    }
}

When i give the input: 10 this is the output:

Enter the number:
10
Result = 2401
Press any key to continue . . .

pls help.

I use Visual Studio 2019 (community edition)

1 Answers1

0

Console.Read() gives you the next character value (i.e: it gives you a valid char value or -1), not the value of the next input number.

Instead you must use Console.ReadLine() and parse it with double.TryParse(string, out double):

Console.WriteLine("Enter the number: ");
// Get the next line input
string input = Console.ReadLine();
// Try to parse it as a double
if (double.TryParse(input, out double num)) {
    // On true we have a number
    Console.WriteLine("Result = " + num*num);
} else {
    // On fail we couldn't parse it.
    Console.WriteLine("Error, please input a number.");
}
Ender Look
  • 2,303
  • 2
  • 17
  • 41