When I type broken number, it removes the comma and sums as integer

4
    static void Main(string[] args)
    {
        Console.Write("Digite sua primeira nota: ");
        double n1 = Convert.ToDouble(Console.ReadLine());
        Console.Write("Digite sua segunda nota: ");
        double n2 = Convert.ToDouble(Console.ReadLine());
        double resultado = (n1 + n2) / 2;
        Console.WriteLine("A Média é {0}", resultado);
        Console.ReadKey();
    }
    
asked by anonymous 13.09.2017 / 06:24

2 answers

7

You probably need to address the issue of culture. However, several errors can occur when typing. If you can not convert correctly you can not let the account.

using static System.Console;

public class Program {
    public static void Main(string[] args) {
        System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("pt-BR");
        Write("Digite sua primeira nota: ");
        double n1;
        if (!double.TryParse(ReadLine(), out n1)) {
            Write("nota digitada errada, estou encerrando, pode tentar novamente");
            return;
        }
        Write("Digite sua segunda nota: ");
        double n2;
        if (!double.TryParse(ReadLine(), out n2)) {
            Write("nota digitada errada, estou encerrando, pode tentar novamente");
            return;
        }
        WriteLine($"A Média é {(n1 + n2) / 2}");
    }
}

See running on Coding Ground . Also put it in GitHub for future reference .

    
13.09.2017 / 06:46
6

The source of the problem is your Regional Settings (Windows), my computer is American regional, use dot in decimal places, so your program works using points.

You can solve by forcing your application to use

System.Globalization.CultureInfo

However, your application will be fixed to the standard you define, if you distribute it to other regions, you will have problems.

    
13.09.2017 / 09:34