1

This program should work for both the condition , atleast i think, but for some values it's not working as supposed.

static void Main(string[] args)
{
    double num, temp = 0;
    double frac;
    int j = 1;

    num = 1034.264;            
    do
    {
        j = j * 10;
        Console.WriteLine(j);
        temp = num * j;
        Console.WriteLine(temp);
    }
    while ((temp % 10)!=0);
}

For value 1034.347 , its working fine --

working for 1034.347

but for value 1034.235 not working 1034.235 it is going to infinite

Ashish P.
  • 51
  • 5
  • 3
    I don't see why people have down voted this question - it is perfectly reasonable and well asked. – Scrobi Jul 13 '17 at 08:23
  • 1
    I agree, it's well written with expected and actual results documented (although doing that in-line would be better). Although it's tempting to close as a duplicate, my feeling that it deserves a short answer and a link to the "canonical" floating point question. – Bathsheba Jul 13 '17 at 08:24
  • Possible duplicate of [Why is modulus operator not working for double in c#?](https://stackoverflow.com/questions/906564/why-is-modulus-operator-not-working-for-double-in-c) – mjwills Jul 13 '17 at 08:59

2 Answers2

9

C# - in order to keep up with the Joneses - has a floating point modulus operator %.

It's unlikely that the resultant binary floating point value will have all its trailing digits set to zero when represented as a decimal number, so (temp % 10)!=0) being false is a rarity.

A workaround in your case would be to work in a factor of 1000 of you values, and use an appropriate integral type.

Reference: Is floating point math broken?

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • I don't see how the factor of a thousand will help in this case; are you assuming that the number will always have three or less non-zero digits after the decimal point? (It seems to me that the purpose of the code is to count the number of non-zero digits after the decimal point, which implies that the number is unknown.) – Harry Johnston Jul 13 '17 at 23:55
0

Comparing floating points numbers with equal is very dangerous, because floating point operations have an error. E.g. the number is not zero, it's 0.0[..]01 - or: near zero. I suggest comparing with a "bandwith":

abs(nubmer) < 0.000001.
Ralph Erdt
  • 537
  • 4
  • 16
  • 1
    A dreadful idea based on sadly very common misconceptions around what binary floating point numbers actually are: they don't have an error; it's just that the floating point set is a sparse subset of the real number set, and that sparseness is not constant so advocating a constant comparative tolerance is poor advice indeed. Do read the link in my answer. – Bathsheba Jul 13 '17 at 08:27