Integer division and remainder

My programs does its function when both numbers are positive but when one of them is negative it does not.

Program objective: Write a program that reads an integer number a and a natural number b, with b > 0, and prints the integer division d and the remainder r of a divided by b.

Remember that, by definition, d i r must be the only integer numbers such that 0 ≤ r < b and d · b + r = a.

1
2
3
4
5
6
7
8
9
10
11
  #include <iostream>
using namespace std;

int main(){
	int a,b;
	b > 0;
	cin >> a >> b;
	int d = a/b;
	int r = a%b;
	cout << d << " " << r << endl;
}


In my program:
32/6 = 5 2 (division and remainder)
-32/6 = -5 -2 (division and remainder)

What program is supposed to do:
32/6 = 5 2 (division and remainder)
-32/6 = -6 4 (division and remainder)


Tell me step by step and why you do that, thanks
Last edited on
Hi,

So you want the program to display the division and remainder

-32/6 = -6 4 (division and remainder)

That is incorrect (at least mathematically)

does your program specifies something for negative integer?

Hi,

So you want the program to display the division and remainder

-32/6 = -6 4 (division and remainder)


That is incorrect (at least mathematically)

does your program specifies something for negative integer?


6 · (-6) = -36
-36 + 4 = -32

How is this wrong: -32/6 = -6 4 (division and remainder)

Program objective: Write a program that reads an integer number a and a natural number b, with b > 0, and prints the integer division d and the remainder r of a divided by b.

Remember that, by definition, d i r must be the only integer numbers such that 0 ≤ r < b and d · b + r = a.
Last edited on
Hello Oriol Serrabassa,

Your program works fine. Recheck your math or your expectations.

Add these two lines at the end of your Program to check the math of the program
1
2
cout << "\n Interger division a / b = " << d << " Remainder a % b = " << r << endl;
cout << "\n d * b + r = a = " << d * b + r << endl;


Not sure if that helps, but that's the way it is,

Andy
I know my programs works fine but it doesn't do what is supposed to.
It does not give a positive remainder

0 ≤ r < b and d · b + r = a.
Last edited on
-32/6 = -5 -2
-5*6 + -2 = -32

that is also correct IMO....

If you don't want remainder -ve you may use a absolute function to convert it to positive, but it won't then give you the d · b + r = a which it naturally gives now
Got it to work myself

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main(){
	int a,b;
	cin >> a >> b;
	int d = a/b;
	int r = a%b;
	if (r < 0){
		d = d-1;
		int s = d*b;
		r = -s+a;
	}
	cout << d << " " << r << endl;
}
Topic archived. No new replies allowed.