📜  C++ div()

📅  最后修改于: 2020-09-25 08:48:39             🧑  作者: Mango

C++中的div() 函数计算整数和两个数字除法的余数。

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

数学上

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()参数

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

示例:div() 函数在C++中如何工作?

#include 
#include 
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