运用C语言while编写程序,键盘输入整数n的值,计算1+1/1!+1/2!+1/3!+......+1/n!的值并输出
时间: 2023-10-30 13:05:08 浏览: 52
非常感谢您的提问。以下是使用C语言while循环计算1 1/1! 1/2! 1/3! ...... 1/n!的值并输出的程序:
```
#include <stdio.h>
int main()
{
int n, i;
double sum=1.0, fac=1.0;
printf("请输入整数n的值:");
scanf("%d",&n);
i=1;
while(i<=n)
{
fac=fac*i;
sum=sum+1.0/fac;
i++;
}
printf("1+1/1!+1/2!+1/3!+...+1/n!=%lf\n",sum);
return 0;
}
```
您可以将上述代码复制并粘贴到您的C语言编译器中进行运行。如果您对程序有任何疑问,请随时向我提问。
相关问题
用C语言while语句编写1+1/2+1/3+...+.1/n的值,要求n用键盘输入
以下是使用C语言while语句编写1+1/2+1/3+...+.1/n的值的代码,其中n为键盘输入的正整数:
```c
#include <stdio.h>
int main() {
int n, i = 1;
double sum = 0;
printf("请输入一个正整数n:");
scanf("%d", &n);
while (i <= n) {
sum += 1.0 / i;
i++;
}
printf("1+1/2+1/3+...+1/n的值为:%.4f\n", sum);
return 0;
}
```
用C语言编写程序:从键盘读入一个大于2的正整数n,求1+2+…+n之和
以下是使用C语言编写程序,从键盘读入一个大于2的正整数n,求1+2+…+n之和的代码:
```c
#include <stdio.h>
int main() {
int n, sum = 0;
printf("请输入一个大于2的正整数n:");
scanf("%d", &n);
while (n <= 2) {
printf("输入错误,请重新输入一个大于2的正整数n:");
scanf("%d", &n);
}
for (int i = 1; i <= n; i++) {
sum += i;
}
printf("1+2+...+%d=%d\n", n, sum);
return 0;
}
```
程序的运行过程如下:
```
请输入一个大于2的正整数n:5
1+2+...+5=15
```
程序首先提示用户输入一个大于2的正整数n,如果用户输入的数不合法(小于等于2),程序会一直提示用户重新输入,直到输入正确为止。然后,程序使用for循环计算1到n的和,并将结果输出。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.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)
![](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)