用C语言以下程序的功能是从键盘输入正整数m的值,求n使 n!≤m≤(n+1)!。例如输入726,则输出n=6。请完善程序。
时间: 2023-05-30 07:04:44 浏览: 154
```c
#include <stdio.h>
int main() {
int m;
printf("请输入一个正整数m:");
scanf("%d", &m);
int n = 1;
while (n * (n + 1) / 2 <= m) {
n++;
}
printf("n=%d\n", n - 1);
return 0;
}
```
解释:首先从键盘输入一个正整数m,然后初始化n为1。接着用while循环,判断n * (n + 1) / 2 是否小于等于m,如果是,则继续循环,n加1;如果不是,则跳出循环,此时n-1就是满足条件的最大整数n。最后输出n-1的值即可。
相关问题
c语言从键盘输入一个正整数n,求 1 + 1/1!+1/2!+…+ 1/n!
以下是C语言实现求和的代码:
```c
#include.h>
#include<stdlib.h>
int fac(int n) //阶乘函数
{
int i = 0;
int y = 1; //用来存返回值
if (0 == n || 1 == n) {
return 1;
}
else {
for (i = 2; i <= n; i++) {
y *= i;
}
return y;
}
}
double sum(int n) //求和函数
{
int i = 0; //循环变量
double sum = 0; //和
for (i = 1; i <= n; i++) {
sum += 1.0 / fac(i);
}
return sum;
}
int main() {
int n = 0;
printf("请输入n:>");
scanf("%d", &n);
printf("sum = %lf\n", sum(n));
system("pause");
return 0;
}
```
这段代码首先定义了一个阶乘函数`fac`,用于计算n的阶乘。然后定义了一个求和函数`sum`,在该函数中调用了阶乘函数`fac`来计算每一项的值,并将其累加到总和中。最后,在`main`函数中,从键盘输入一个正整数n,并调用求和函数`sum`来计算1 + 1/1! + 1/2! + … + 1/n!的值,并输出结果。
编程c语言求1!+2!+3!++n!,要求n从键盘输入(n≥1)
以下是C语言求1!+2!+3!+...+n!的代码,其中n从键盘输入:
```c
#include <stdio.h>
int main() {
int n, i, j, factorial, sum = 0;
printf("请输入一个正整数n:");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
factorial = 1;
for (j = 1; j <= i; j++) {
factorial *= j;
}
sum += factorial;
}
printf("1!+2!+3!+...+n!的和为:%d\n", sum);
return 0;
}
```
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)