Check if a double is evenly divisible by another double in C?

前端 未结 7 2091
故里飘歌
故里飘歌 2020-12-10 02:41

How can I check if a double x is evenly divisible by another double y in C? With integers I would just use modulo, but what would be the correct/best way to do it with doubl

7条回答
  •  伪装坚强ぢ
    2020-12-10 03:20

    If you want to be absolutely precise, you could used fixed-point math. That is, do everything with ints, but ints that are (in your case) some power of 10 of the value they actually represent.

    Say the user enters 123.45 and 6789.1. First, you want to make sure you've got the same number of decimal places, so add trailing zeros to the one with fewer decimal places. That gives us 123.45 and 6789.10 (now both with 2 decimal places). Now just remove the decimal point, to get 12345 and 678910. If one divides into the other evenly, that's your answer.

    This works because removing the decimal point multiplies both by the same constant (100 in the example above). (x * 100) / (y * 100) == x / y

    A few things to be careful about: if you read the integer part and fractional part as ints, be careful that you don't lose leading zeros on the fractional part. (eg: 0.1 and 0.0001 are not the same number!) Also, if there are enough decimal places you can overflow. You probably want to at least use a long.

    You could also do the computation with doubles, but it'll be less precise. To do it that way, do the division, and then compare the difference between the result and the rounded result. If within some small tolerance, then it divides evenly.

提交回复
热议问题