C++ div()

div() 函数在 <cstdlib> 头文件中定义。

数学上,

quot * y + rem = x

div() 原型 [截至 C++ 11 标准]

div_t div(int x, int y);
ldiv_t div(long x, long y);
lldiv_t div(long long x, long long y);

它接受两个参数 xy,并返回 x 除以 y 的整数商和余数。

quot 是表达式 x / y 的结果。 余数 rem 是表达式 x % y 的结果。


div() 参数

  • x - 被除数
  • y - 除数

div() 返回值

div() 函数返回类型为 div_tldiv_tlldiv_t 的结构。 这些结构中的每一个都包含两个成员:quotrem。 它们的定义如下:

div_t:
struct div_t {
  int quot;
  int rem;
};

ldiv_t:
struct ldiv_t {
  long quot;
  long rem;
};

lldiv_t:
struct lldiv_t {
  long long quot;
  long long rem;
};

示例:C++ div() 函数

#include <iostream>
#include <cstdlib>
using namespace std;

int main() {

  div_t result1 = div(51, 6);

  cout << "Quotient of 51/6 = " << result1.quot << endl;
  cout << "Remainder of 51/6 = " << result1.rem << endl;

  ldiv_t result2 = div(19237012L,251L);

  cout << "Quotient of 19237012L/251L = " << result2.quot << endl;
  cout << "Remainder of 19237012L/251L = " << result2.rem << endl;

  return 0;
}

输出

Quotient of 51/6 = 8
Remainder of 51/6 = 3
Quotient of 19237012L/251L = 76641
Remainder of 19237012L/251L = 121

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战