- C 标准库
- C 库 - 首页
- C 库 - <assert.h>
- C 库 - <complex.h>
- C 库 - <ctype.h>
- C 库 - <errno.h>
- C 库 - <fenv.h>
- C 库 - <float.h>
- C 库 - <inttypes.h>
- C 库 - <iso646.h>
- C 库 - <limits.h>
- C 库 - <locale.h>
- C 库 - <math.h>
- C 库 - <setjmp.h>
- C 库 - <signal.h>
- C 库 - <stdalign.h>
- C 库 - <stdarg.h>
- C 库 - <stdbool.h>
- C 库 - <stddef.h>
- C 库 - <stdio.h>
- C 库 - <stdlib.h>
- C 库 - <string.h>
- C 库 - <tgmath.h>
- C 库 - <time.h>
- C 库 - <wctype.h>
- C 标准库资源
- C 库 - 快速指南
- C 库 - 有用资源
- C 库 - 讨论
C 库 - ldiv() 函数
C 的stdlib 库 ldiv() 函数用于将长整型分子除以长整型分母。然后返回长整型商和余数。
例如,将长整型分子 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
广告