|
使用VS2019
ISO C++14 标准 (/std:c++14)
阶乘求和
求1+2!+3!+...+20!的和。
由于20!值为2432902008176640000,19位数值,一般的数据类型时满足不了了,
所以只能用最大的long double,有效数字18~19,-1.2*10^-4932~1.2*10^4932
| 类型 | 比特(位)数 | 有效数字 | 数值范围 | | float | 32 | 6~7 | -3.4*10^38~+3.4*10^38 | | double | 64 | 15~16 | -1.7*10^-308~1.7*10^308 | | long double | 128/ | 18~19 | -1.2*10^-4932~1.2*10^4932 |
采用%f 是输出 float 型变量;%f 是输出 double 型变量;%Lf 是输出 long double 型变量。
//求1+2!+3!+...+20!的和。
#include<stdio.h>
int main() {
//在16位机器中,int占16位,取值范围为前面所说的-32768~32767(-2^16~2^16-1)。
//而在32位和64位机器中,int占32位,取值范围为-2147483648~2147483647(-2^32~2^32-1)。
//ISO/ANSI C规定,int类型的最小范围为-32768到32767。
//32位平台 unsigned long在内存中占四个字节,范围为0~2^32-1
long double sum = 0, temp = 1;
for (int i = 1; i <= 20; i++) {
temp = temp * i;
sum = sum + temp;
}
//输出无符号的长整型,正确的形式应该是%ld
printf("1+2!+3!+...+20!的和为:%Lf", sum);
}

|