我一直在尝试创建简单的程序,将输入数字分成比索钞票。我需要的输出是
Enter Amount: 7350
P1000: 7
P500: 0
P200: 1
P100: 1
P50: 1
P20:0
P10:0
P5:0
P1:0
这是我的初始代码:
#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;
}
但我得到的输出是
input number in pesos: 7350
P1000 = 7
P500 = 0
P200 = 1
P100 = 1
P50 = 1
P20 = 0
P10 = 1
P1= 0
所以经过一番修改后,我使用了这段代码,效果很好!
#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;
}
所以我的问题是,为什么使用复合模运算符是如何工作的?它与常规的模运算符有何不同?我不认为数学是问题,而是代码的处理方式。这是我学习 C++(和一般编程)的最初几周,如果能解决我的一些困惑会很好。先感谢您。