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

后端 未结 5 1025
难免孤独
难免孤独 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:33

    Well, you could do what the modulo operator typically does internally.

    Inside a loop, substract b from a repeatedly. When this is no longer possible, the number you're left with is your answer.

    Here's a code example. If you're trying to accomplish this for decimal numbers, be mindful of rounding errors for floating-point values.

    double result = a;
    while(result - b >= 0) {
        result -= b;
    }
    return result;
    

    Note that if you're working with integers, and you're allowed to use the division operator, you don't need to use a loop.

    However, do keep in mind that all that division does is repeated subtraction. If this is for pedagogical purposes, I think it's cooler to do it my way.

提交回复
热议问题