0

I am into this code but I need an explanation as to why

            int n = 6;
            int count = 0;
            double end = Math.Sqrt(n);
            for (int i = 1; i < end; i++)
            {
                if (n % i == 0)
                    count += 2;
            }
            Console.WriteLine(end * end + " - " + n);
            Console.WriteLine(end * end == n);
            if (end * end == 6)  
                Console.WriteLine("why");

returns false in the second Console.Writeline but if n=9 returns true

CodeRed
  • 905
  • 1
  • 6
  • 24
  • Comparing floating point values for equality doesn't work that way. See https://learn.microsoft.com/de-de/dotnet/api/system.double.equals?view=netframework-4.8 and https://stackoverflow.com/questions/3874627/floating-point-comparison-functions-for-c-sharp – Markus Deibel Jul 24 '19 at 10:34
  • `end * end = 5.9999999999999991`. – SᴇM Jul 24 '19 at 10:35
  • @AFriend the first `Console.Writeline` shows the value of `end * end` together with `n` – CodeRed Jul 24 '19 at 10:36
  • 1
    Mostly likely a fitting duplicate https://stackoverflow.com/questions/1420752/is-double-multiplication-broken-in-net) similar questions are asked every couple of days – TheGeneral Jul 24 '19 at 10:37
  • [Fiddling](https://dotnetfiddle.net/8a59Gl) around your example, try with `9`.. – Sinatr Jul 24 '19 at 11:28

1 Answers1

0

end is a double and is equal to the square root of 6. Even though end * end is supposed to be 6, you are comparing double to int with the = sign which is a big no-no.
In this answer you can see the correct way to do so.

pappbence96
  • 1,164
  • 2
  • 12
  • 20