-1

Simply put, I'm very new and I do not understand why I need total to be a double, my teacher put it as a float in his program, but it doesn't work for me.

        int choix;
        double total = 0;

        do
        {
            Console.WriteLine("Menu\n\n");
            Console.WriteLine("1 - Pizza 3.25$\n");
            Console.WriteLine("2 - Poutine 2.75$\n");
            Console.WriteLine("3 - Liqueur 1.25$\n");
            Console.WriteLine("4 - Fin\n\n");

            Console.WriteLine("Votre choix(1 - 4)");
            choix = int.Parse(Console.ReadLine());

            switch(choix)
            {
                case 1:total = total + 3.25;
                    break;
                case 2:total = total + 2.75;
                    break;
                case 3:total = total + 1.25;
                    break;
                case 4:Console.WriteLine("Voici le total " + total);
                    break;
                default:Console.WriteLine("Erreur de choix");
                    break;
            }
        }
        while (choix != 4);

Sorry for this dumb question, but I cannot find answers anywhere.

Evhan
  • 1
  • 1

1 Answers1

2

Basically because of how c# interprets the code, c# doesnt know whether your decimal numbers will overflow or not, so it automatically assign all floating values as a double (which can actually hold more values than a float). So what you need to do in order to the compiler understand that you actually want a float, is to add an f at the end of the numbers.

int choix;
float total = 0;

do
{
    Console.WriteLine("Menu\n\n");
    Console.WriteLine("1 - Pizza 3.25$\n");
    Console.WriteLine("2 - Poutine 2.75$\n");
    Console.WriteLine("3 - Liqueur 1.25$\n");
    Console.WriteLine("4 - Fin\n\n");

    Console.WriteLine("Votre choix(1 - 4)");
    choix = int.Parse(Console.ReadLine());

    switch (choix)
    {
        case 1:
            total = total + 3.25f;
            break;
        case 2:
            total = total + 2.75f;
            break;
        case 3:
            total = total + 1.25f;
            break;
        case 4:
            Console.WriteLine("Voici le total " + total);
            break;
        default:
            Console.WriteLine("Erreur de choix");
            break;
    }
}
while (choix != 4); 
nalnpir
  • 1,167
  • 6
  • 14