Division Algorithm

Ok, I have this homework for class due next week and I was trying to get a jump start and I can't seem to figure out why I keep getting the wrong answers.

Basically I am writing a very simple program that will fix negative remainders.

The assignment is this:
Let's recall the Division Algorithm, from Chapter 2. I will restate it here, in terms of the corollary that neatly sums up the complete result:
Let a and b be integers, with b non zero. Then there exist unique integers q and r such that
a = bq + r, with 0 <= r < |b|

The problem here for normal computer use is that the operators / and % in C++ (and in other languages as well) do NOT act this way. If you set q = a / b, with r = a % b and a < 0, you will get a remainder that is negative.
That is NOT what the theorem above wants! It ALWAYS wants a non-negative remainder!

Now, to get that you will need to play with the "quotient". In general, if you have set
q = a / b;
r = a % b;
and r is negative, you can add 1 to q if q > 0 or subtract 1 from q otherwise, and recalculate r = a - bq, and that will fix it. I want you to write a C++ program that will input a and b, calculate q and r this way and output results, testing whether a == bq + r with r being at least zero and less than |b|, and complaining if any of this is false.


My code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>


using namespace std;

int main() {
	int a=0;
	int b=0;
	int r=0;
	int q=0;
	cout <<"Enter the two numbers"<<endl;
	cout <<"A is:";
	cin >> a;
	cout <<"B is:";
	cin >> b;
	q = a /b;
	r = a % b;
	if (r <0){
	if (q > 0){
	q +=1;
	}
	if (q < 0){
	q -=1;
	}
	r = a - (b * q);
	}
	cout << "\n\n\nResults:"<<endl;
	cout <<"Q is: "<< q <<endl;
	cout <<"R is: "<<r<<endl;
	cin.ignore();
	cin.get();

}


What I keep getting when I input (for example) A: -20 and B: 3 is:
Q is -7
R is 1


when r is supposed to be 2.

What am I missing?
Topic archived. No new replies allowed.