I have been trying to create simple program which divides an input number into peso bills. The output I need is
Enter Amount: 7350
P1000: 7
P500: 0
P200: 1
P100: 1
P50: 1
P20:0
P10:0
P5:0
P1:0
and this was my initial code:
#include <iostream>
using namespace std;
int main()
{
int const P1000(1000);
int const P500(500);
int const P200(200);
int const P100(100);
int const P50(50);
int const P20(20);
int const P10(10);
int const P1(1);
int input;
//input number
cout<<"input number in pesos: ";
cin>>input;
cout<<"P1000 = "<<input/P1000<<endl;
cout<<"P500 = "<<(input%1000)/P500<<endl;
cout<<"P200 = "<<(input%500)/P200<<endl;
cout<<"P100 = "<<(input%200)/P100<<endl;
cout<<"P50 = "<<(input%100)/P50<<endl;
cout<<"P20 = "<<(input%50)/P20<<endl;
cout<<"P10 = "<<(input%20)/P10<<endl;
cout<<"P1= "<<(input%10)/P1<<endl;
return 0;
}
but the output I get is
input number in pesos: 7350
P1000 = 7
P500 = 0
P200 = 1
P100 = 1
P50 = 1
P20 = 0
P10 = 1
P1= 0
so after a bit of tinkering I used this block of code which worked wonders!
#include <iostream>
using namespace std;
int main()
{
int const P1000(1000);
int const P500(500);
int const P200(200);
int const P100(100);
int const P50(50);
int const P20(20);
int const P10(10);
int const P1(1);
int input;
//input number
cout<<"input number in pesos: ";
cin>>input;
cout<<"P1000 = "<<input/P1000<<endl;
cout<<"P500 = "<<(input%=1000)/P500<<endl;
cout<<"P200 = "<<(input%=500)/P200<<endl;
cout<<"P100 = "<<(input%=200)/P100<<endl;
cout<<"P50 = "<<(input%=100)/P50<<endl;
cout<<"P20 = "<<(input%=50)/P20<<endl;
cout<<"P10 = "<<(input%=20)/P10<<endl;
cout<<"P1= "<<(input%=10)/P1<<endl;
return 0;
}
So my question is, how why did using the compound modulo operator work? How is it different from the regular modulo operator? I don't think the math is the problem but the way the code is handled. This is my first few weeks of learning C++ (and programming in general) and it would be nice to clear up some of my confusion. Thank you in advance.
Here is a small program to illustrate the difference:
#include <iostream>
int main()
{
int i = 256;
std::cout << "i: " << i << ", i % 100: " << (i % 100) << std::endl;
std::cout << "i: " << i << ", i % 12: " << (i % 12) << std::endl;
std::cout << "i: " << i << ", i % 3: " << (i % 3) << std::endl;
std::cout << std::endl;
std::cout << "i: " << i << ", i %= 100: " << (i %= 100) << std::endl;
std::cout << "i: " << i << ", i %= 12: " << (i %= 12) << std::endl;
std::cout << "i: " << i << ", i %= 3: " << (i %= 3) << std::endl;
}
This outputs (fixed spaces to be nicer):
i: 256, i % 100: 56
i: 256, i % 12: 4
i: 256, i % 3: 1
i: 256, i %= 100: 56
i: 56, i %= 12: 8
i: 8, i %= 3: 2
As you can see in the first part, the regular modulo operator leaves i
at the original value. This means that we get 256 modulo 100, 12 and 3.
However, in the second part the compound modulo operator keeps changing i
, so that the next modulo only operates on the remainder.