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);
它接受两个参数 x 和 y,并返回 x 除以 y 的整数商和余数。
商 quot 是表达式 x / y
的结果。 余数 rem 是表达式 x % y
的结果。
div() 参数
- x - 被除数
- y - 除数
div() 返回值
div()
函数返回类型为 div_t
、ldiv_t
或 lldiv_t
的结构。 这些结构中的每一个都包含两个成员:quot
和 rem
。 它们的定义如下:
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
另请阅读