复合模如何在 C++ 中工作?

How Does the Compound Modulo Work in C++?

我一直在尝试创建一个简单的程序,将输入的数字分成比索钞票。我需要的输出是

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++(和一般编程)的头几周,如果能消除我的一些困惑会很好。提前谢谢你。

这里有一个小程序来说明区别:

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

这个输出(固定空格更好):

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

正如您在第一部分中所见,常规模运算符将 i 保留为原始值。这意味着我们得到 256 模 100、12 和 3。

然而,在第二部分中,复合模运算符不断变化i,因此下一个模只对余数进行运算。