Yet Another C++ Dilemma

Binary Ranger

Banned
Messages
67
Location
Midgard
Hello all! If you haven't figured it out yet, I'm in a programming class and am in need of some help. Now before I go any further, let me clarify that I am not trying to get you to do my work for me. I honestly am trying to figure this out, but it is something of a stumper for me.

They want me to make a program that will display the dividend, divisor, remainder, and quotient when the user inputs the divisor and the dividend by using the division algorithm.

In case you're rusty or have no idea what I am talking about, the division algorithm is as follows: (At least this is how the class presented it to us)

a = qd + r where 0 <= r < |d|

Where a equals the dividend, d equals the divisor, q equals the quotient and r equals the remainder.

Now the program will display this after the user puts in the dividend and divisor:

If a = 17 and d = 3, then q = 5 and r = 2, since 17 = (5)(3) + 2.

The problem I am having is that they want us to be able to use negative numbers and this creates a problem with the math I have put into it. If I'm confusing you, this is what they want:

If a = 17 and d = -3, then q = -5 and r = 2, since 17 = (-5)(-3) + 2.
or
If a = -17 and d = 3, then q = -6 and r = 1, since -17 = (-6)(3) + 1.
or
If a = -17 and d = -3, then q = 6 and r = 1, since -17 = (6)(-3) + 1.

But I cannot get it to work with negative numbers without r being a negative number. And that cannot happen because r cannot be less than 0.

They also gave us this cryptic message in the assignment:

"The C++ operators for integer division do not conform to the division algorithm. Explain in output displayed to the user of the program when to expect results that disagree with the division algorithm. The program should not attempt to resolve this issue. "

And that's about all I have to work with. I toyed with the algebra but I cannot get the algorithm to work with negative numbers. I can't think of an alternative way to make the program work with negative numbers either. Like using a different formula to calculate in appropriately. I'd appreciate any assistance.
 
Why not just use the modulo operator to compute the remainder? Or are you required to use the algorithm above?

You could always kinda cheat and explicitly check if R is negative, and then just make it positive.

Code:
if(r < 0)
    r = r * -1;
 
Back
Top Bottom