1

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

#include <iostream>
using namespace std;

int main(){
    int a,b;
    b > 0;
    cin >> a >> b;
    int d;
    d = a/b;
    int r;
    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)
  • Please copy the code here.. – amchacon Sep 20 '16 at 16:32
  • 4
    Look up "modulo" or "modulus" in your favorite C++ or mathematical references. You could also search Wikipedia! – Thomas Matthews Sep 20 '16 at 16:33
  • 2
    [FYI] C++ modulo does not work like it does in pure mathematics. see: http://stackoverflow.com/questions/13683563/whats-the-difference-between-mod-and-remainder – NathanOliver Sep 20 '16 at 16:40
  • 2
    If you'd posted your code as text instead of as a picture you wouldn't be getting so many recommendations to use `%`. Nobody wants to look at pictures of code. – molbdnilo Sep 20 '16 at 16:43
  • [Modulo operation with negative numbers](http://stackoverflow.com/q/11720656/995714) – phuclv Sep 21 '16 at 14:02

2 Answers2

2

You are looking for the modulus operator, '%'.

int a = 5 % 2;
cout << a << endl;

The modulus operator returns the remainder of the first value divided by the second.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
0

I got it to work myself. For anyone who needs a program like this here it is:

#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;
}