Write a program to find remainder of dividing two numbers, without using % operator? In Java

后端 未结 5 1023
难免孤独
难免孤独 2021-01-03 02:21

How to find the remainder of dividing two numbers without using the modulo operator!! My teacher gave me this exact exercise and It\'s only my 5th lecture in a course calle

5条回答
  •  星月不相逢
    2021-01-03 02:55

    It makes no sense to perform % on double or float numbers, because floating point numbers actually each represent a very small range of values, rather than an exact value. Often, the internal representation of a floating point number isn't the same number in that range as the actual decimal that you used to create the number. This means that the result of % is formally undefined, for floating point types.

    If you try 0.3 % 0.1 in Java, you actually get 0.09999999999999998, which seems at first sight to be incorrect; but this makes as much sense as any other result, given what floating point numbers really represent.

    Here is the simplest solution for working out %, without actually using %.

    a - b * (long)(a/b);
    

    It will perform better than an answer that does repeated subtraction, because it doesn't have to loop over and over.

    But this solution inevitably falls victim to the same trap as certain other answers on this page, namely that the "correct" answer is formally undefined.

    This solution will also give overflow problems if your numbers are extremely large.

提交回复
热议问题