C 庫 - ldiv() 函式



C 的stdlibldiv() 函式用於將長整型分子除以長整型分母。然後返回長整型商和餘數。

例如,將長整型分子 100000L 和長整型分母 30000L 傳遞給 ldiv() 函式以獲得結果。透過計算 'result.quot' (100000L/30000L = 3) 獲取商,透過計算 'result.rem' (100000L%30000L = 10000) 獲取餘數。

語法

以下是 ldiv() 函式的 C 庫語法:

ldiv_t ldiv(long int numer, long int denom)

引數

此函式接受以下引數:

  • numer − 表示長整型分子。

  • denom − 表示長整型分母。

返回值

此函式返回一個結構體值,該結構體定義在 <cstdlib> 中,包含兩個成員:長整型 'quot' 和長整型 'rem'。

示例 1

在這個例子中,我們建立了一個基本的 C 程式來演示 ldiv() 函式的使用。

#include <stdio.h>
#include <stdlib.h>

int main () {
   ldiv_t res;

   res = ldiv(100000L, 30000L);

   printf("Quotient = %ld\n", res.quot);

   printf("Remainder = %ld\n", res.rem);
   
   return(0);
}

輸出

以下是輸出:

Quotient = 3
Remainder = 10000

示例 2

這是另一個示例,我們將分子和分母都作為負長整型傳遞給 ldiv() 函式。

#include <stdio.h>
#include <stdlib.h>
int main()
{
   long int numerator = -100520;
   long int denominator = -50000;
   
   // use div function	
   ldiv_t res = ldiv(numerator, denominator);
   
   printf("Quotient of 100/8 = %ld\n", res.quot);
   printf("Remainder of 100/8 = %ld\n", res.rem);
   
   return 0;
}

輸出

以下是輸出:

Quotient of 100/8 = 2
Remainder of 100/8 = -520

示例 3

下面的 C 程式計算兩個長整型相除時的商和餘數。

#include <stdio.h>
#include <stdlib.h>

int main() {
   // use ldiv() function
   ldiv_t res = ldiv(50, 17);
   // Display the quotient and remainder
   printf("ldiv(50, 17) gives quotient = %ld and remainder = %ld\n", res.quot, res.rem);
   return 0;
}

輸出

以下是輸出:

ldiv(50, 17) gives quotient = 2 and remainder = 16
廣告
© . All rights reserved.