21xrx.com
2025-03-27 16:44:02 Thursday
文章检索 我的文章 写文章
C++代码示例:取余数
2023-06-28 21:00:08 深夜i     14     0
C++ 代码 取余 模除 取模

在C++编程中,取余数是一种非常常见的操作。取余数的符号是“%”,通常用于对一个数进行除法运算后,取得余数。下面是一些C++代码示例,用于说明如何使用取余数。

代码示例1:获取余数

下面的代码片段演示了如何使用%符号来获取两个整数之间的余数:

#include <iostream>
using namespace std;
int main()
  int a = 10;
  int b = 3;
  int c = a % b;
  cout << "The remainder is " << c << endl;
  return 0;

输出:

The remainder is 1

解释:

在这个代码示例中,我们通过使用%符号来获取a除以b的余数。在这种情况下,a = 10,b = 3, 通过计算(10/3),我们可以得到商为3,余数为1,因此,代码中的c被赋值为1。

代码示例2:判断奇偶性

下面的代码示例演示了如何使用%符号来判断一个整数是奇数还是偶数:

#include <iostream>
using namespace std;
int main()
{
  int n;
  cout << "Input an integer: " << endl;
  cin >> n;
  if (n % 2 == 0)
  
    cout << "The integer is even." << endl;
  
  else
  
    cout << "The integer is odd." << endl;
  
  return 0;
}

输出:

Input an integer:
6
The integer is even.

输出:

Input an integer:
7
The integer is odd.

解释:

在这个代码示例中,我们要求用户输入一个整数。然后,我们使用%符号来判断该整数是否为偶数。如果它是偶数,则输出“The integer is even.”如果它是奇数,则输出“The integer is odd.”

总结:

取余数是C++编程非常基础的知识,在编写程序时经常用到。它的应用范围非常广泛,可以用来判断奇偶性、提取金额、判断分页等等。我们需要熟练掌握这个操作符号,才能写出高效的程序,提高自己的编程能力。

  
  

评论区