在 C++ 中使用模数运算符
    
    Jinku Hu
    2023年10月12日
    
    C++
    C++ Modulo
    
 
本文将介绍如何在 C++ 中使用模数运算符。
使用%运算符计算除法中的余数
    
模 (%)运算符的标准功能是计算除法的余数。语句的返回值-x % y 代表 x 除以 y 后剩下的余数。模数运算符的定义是两个操作数必须是整数,并且除数是非零。下面的例子演示了模数运算符在不同的有符号整数对中的应用。请注意,如果要使用 printf 函数将字符%打印到控制台,我们应该使用%%。
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
int main() {
  vector<int> ivec1{24, 24, -24, -24, 24};
  vector<int> ivec2{7, 8, -8, -7, -6};
  for (size_t i = 0; i < ivec1.size(); ++i) {
    printf("% -d %% % -d = % -d\n", ivec1[i], ivec2[i], ivec1[i] % ivec2[i]);
  }
  cout << endl;
  return EXIT_SUCCESS;
}
输出:
 24 %  7 =  3
 24 %  8 =  0
-24 % -8 =  0
-24 % -7 = -3
 24 % -6 =  0
使用%运算符在 C++ 中生成小于给定最大数的随机整数
模数运算符的另一种用法是控制随机数生成器只提供小于特定整数的数字。程序员根据对随机性质量的需要,负责选择随机数生成工具箱,但这两种方法都可以与%结合起来,指定生成数字的上限。在这种情况下,我们使用 rand 函数,其返回值与所需的最大值使用 modulo 运算符配对。
#include <ctime>
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
constexpr int MAX = 1000;
constexpr int NUMS_TO_GENERATE = 10;
int main() {
  vector<int> ivec1{24, 24, -24, -24, 24};
  vector<int> ivec2{7, 8, -8, -7, -6};
  std::srand(std::time(nullptr));
  for (int i = 0; i < NUMS_TO_GENERATE; i++) {
    cout << rand() % MAX << "; ";
  }
  cout << endl;
  cout << endl;
  return EXIT_SUCCESS;
}
输出:
98; 194; 398; 190; 782; 550; 404; 557; 509; 945;
在 C++ 中使用库定义的函数对象来替换%运算符
C++ 标准库定义了多个代表传统算术、关系和逻辑运算符的类。这些类称为函数对象,其名称为 std::plus<Type>、std::modulus<Type> 等。Type 指定调用运算符的参数类型。下面的代码示例显示了 std::modulus 函数对象在整数向量上的应用。
#include <ctime>
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
int main() {
  vector<int> ivec1{24, 24, -24, -24, 24};
  vector<int> ivec2{7, 8, -8, -7, -6};
  std::modulus<> intMod;
  int mod_of_nums = intMod(ivec1[1], ivec2[1]);
  printf("%d %% %d = %d\n", ivec1[1], ivec2[1], mod_of_nums);
  return EXIT_SUCCESS;
}
输出:
24 % 8 = 0
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
    
