當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C++ ldiv()用法及代碼示例


C++ ldiv() 函數

ldiv() 函數是 cstdlib 頭文件的庫函數。它用於整數除法,它接受兩個參數(分子和分母)並返回一個包含quot() 和rem()。

ldiv() 函數的語法:

C++11:

    ldiv_t ldiv (long int numer, long int denom);

參數:

  • numer– 表示分子的值。
  • denom– 表示分母的值。

返回值:

這個函數的返回類型是ldiv_t, 返回一個包含quot(商)和rem()。

例:

    Input:
    long int n = 123456789;
    long int d = 12345678;
    ldiv_t result;

    Function call:
    result = ldiv(n, d);

    Output:
    result.quot = 10
    result.rem = 9

C++代碼演示ldiv()函數的例子

// C++ code to demonstrate the example of
// ldiv() function

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

// main() section
int main()
{

    long int n = 123456789;
    long int d = 12345678;
    ldiv_t result;

    result = ldiv(n, d);

    cout << "Numerator :" << n << endl;
    cout << "Denominator:" << d << endl;
    cout << "Quotient  :" << result.quot << endl;
    cout << "Remainder :" << result.rem << endl;
    cout << endl;

    n = 999988887777;
    d = 1112223334;

    result = ldiv(n, d);

    cout << "Numerator :" << n << endl;
    cout << "Denominator:" << d << endl;
    cout << "Quotient  :" << result.quot << endl;
    cout << "Remainder :" << result.rem << endl;
    cout << endl;

    n = 100100234;
    d = 9878762536;

    result = ldiv(n, d);

    cout << "Numerator :" << n << endl;
    cout << "Denominator:" << d << endl;
    cout << "Quotient  :" << result.quot << endl;
    cout << "Remainder :" << result.rem << endl;
    cout << endl;

    return 0;
}

輸出

Numerator :123456789
Denominator:12345678
Quotient  :10
Remainder :9

Numerator :999988887777
Denominator:1112223334
Quotient  :899
Remainder :100110511

Numerator :100100234   
Denominator:9878762536
Quotient  :0
Remainder :100100234

參考:C++ ldiv() 函數



相關用法


注:本文由純淨天空篩選整理自 ldiv() Function with Example in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。