Can someone please explain this...

Ok so I was trying to better understand the use of %= so I wrote the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
#include <cmath>
using namespace std;

int main()
{
    int a, b;
    long double c, d;
    c=(a/b);
    d=(a%b);
    cout<<"Please give a and b:"<<endl;
    cin>>a;
    cin>>b;
    cout<<"a/b="<<c<<'\t'<<a/b<<endl;
    cout<<"a%b="<<d<<'\t'<<a%b<<endl;
    
    system("PAUSE");
    return 0;
}

When I ran the program...
Please give a and b:
2
4
a/b=0   0
a%=b=2   2

Why is it not:
a/b=0.5
a%b=0.5
First, you are performing operations with a and b before they have been initialized. They could be junk, they could be 0, they could be anything at all.

Apart from that: you are performing integer division. Even though you are storing the result in a double, the actual division is done with integer values, which means that the remainder is simply thrown away. This means that you should have 0 (as 2 / 4 = 0.5, but you throw away the remainder, hence 0).

Also, you are misunderstanding how the modulo operator works. It gets one number, and returns the remainder when you divide it by a second number. Hence 2 % 4 = 2, because 2 / 4 = 0 remainder 2.
Topic archived. No new replies allowed.