用c语言写一个计算n的阶乘的代码
时间: 2023-03-14 12:36:02 浏览: 158
#include<stdio.h>
int main(){
int i,n;
long long int result = 1;
printf("请输入一个整数:");
scanf("%d",&n);
if(n<0){
printf("抱歉,负数没有阶乘!\n");
}else{
for(i=1;i<=n;i++){
result *= i;
}
printf("%d的阶乘结果是:%lld\n",n,result);
}
return 0;
}
相关问题
用c语言写一个代码求阶乘倒数的和
在C语言中,我们可以编写一个函数来计算给定范围内所有正整数的阶乘,并求它们倒数之和。因为阶乘随着数的增加增长非常快,直接计算可能会导致溢出,所以我们需要使用循环和取模运算来防止这个问题。以下是一个简单的示例代码:
```c
#include <stdio.h>
// 计算n的阶乘
unsigned long long factorial(int n) {
if (n == 0 || n == 1) // 阶乘的基本情况
return 1;
else
return n * factorial(n - 1);
}
// 计算阶乘倒数并累加到总和
double sum_of_reciprocals(int start, int end) {
double sum = 0.0;
for (int i = start; i <= end; ++i) {
unsigned long long fact = factorial(i); // 计算阶乘
double reciprocal = 1.0 / fact; // 取倒数
sum += reciprocal; // 累加
}
return sum;
}
int main() {
int range_start = 1;
int range_end = 5; // 示例范围从1到5
double result = sum_of_reciprocals(range_start, range_end);
printf("The sum of reciprocals of factorials from %d to %d is: %.9f\n", range_start, range_end, result);
return 0;
}
```
用c语言写一个求阶乘的代码
以下是用C语言编写的求阶乘的代码:
```c
#include <stdio.h>
int main() {
int n, i;
unsigned long long factorial = 1;
printf("请输入一个整数:");
scanf("%d", &n);
// 如果 n 是负数,则不能求阶乘
if (n < 0) {
printf("错误!负数没有阶乘。\n");
}
else {
for (i = 1; i <= n; ++i) {
factorial *= i;
}
printf("%d 的阶乘 = %llu\n", n, factorial);
}
return 0;
}
```
在这个程序中,我们定义了一个整数变量 `n` 和一个无符号长整型变量 `factorial`,`n` 用于存储用户输入的整数,`factorial` 用于存储阶乘的结果。程序首先提示用户输入一个整数,然后使用 `scanf()` 函数读入这个整数。接着,程序使用 `for` 循环计算阶乘,并将结果存储在 `factorial` 变量中。最后,程序输出计算结果。
需要注意的是,由于阶乘的结果可能非常大,因此我们使用了无符号长整型变量来存储结果。在计算阶乘时,我们也需要注意溢出的问题。
阅读全文
相关推荐













