0

I wanted to write a very basic BMI calculation for showcasing purposes. However the variable bmi is always 0 because the result of the calculation is a decimal bellow 0 (0,18 0,2352) and so on. I tried hardcoding the numbers for the calculation. I changed the variable type from double to float. But nothing changed. I also don't get any errors or warnings from Visual studio. Can anybody help?

static void Main(string[] args)
{
    Console.WriteLine("BMI rechner");
    double weight;
    double height;
    string name;
    double bmi;
    int x = 1;

    do{
        Console.WriteLine("Bitte gib deinen Namen ein:");
        name = Console.ReadLine();
        Console.WriteLine("Bitte gib dein Gewicht in kg ein:");
        weight = Convert.ToDouble(Console.ReadLine());
        Console.WriteLine("Bitte gib deine Größe in cm ein:");
        height = Convert.ToDouble(Console.ReadLine());
        bmi = 60 / (165 * 165);
    //    bmi = weight / (height * height);

        Console.WriteLine("{0}s BMI ist {1}",name,bmi);
        Console.WriteLine();
        Console.WriteLine("Erneut berechnen(1)? Beenden(0)");
        x = Convert.ToInt32(Console.ReadLine());
    } while (x == 1);

    Console.WriteLine("Vielen dank für das verwenden des BMI rechners.");
    Console.ReadLine();
}
D Stanley
  • 149,601
  • 11
  • 178
  • 240
Julia Z
  • 125
  • 9
  • 3
    Using integer constants returns an integer result. If you want a floating point result use double/decimal constants IE 60.0 / (165.0 * 165.0) – Steve Apr 20 '16 at 15:51
  • God I feel so stupid.... I did change the constants to double but only after hardcoding the calculation. Thank you – Julia Z Apr 20 '16 at 15:52
  • 5
    I *really* wish C# warned about this one. This crops up a lot. Don't feel dumb; many experienced programmers fall into this trap. – Eric Lippert Apr 20 '16 at 15:52
  • We also occasionally see the "dual" of this issue: `long x = some_int * 1000000;` You need to do the conversion to long before the *multiplication* but here it is done before the *assignment*, too late. – Eric Lippert Apr 20 '16 at 15:54
  • @EricLippert I got nailed by this the other day too. I'm surprised IntelliSense doesn't at least give you a green squiggly line indicating a possible runtime problem (not exception). – Drew Kennedy Apr 20 '16 at 15:55
  • Resharper will tag `double bmi = 65 / (165 * 165);` with _Possible loss of fraction_, but unfortunately doesn't notice the potential issue with `long x = some_int * 1000000;` – juharr Apr 20 '16 at 16:21

0 Answers0