c++ 典型循环:s=1!+2!+3!+……+n!,用三种循环编程
时间: 2023-10-05 07:07:41 浏览: 82
C语言编写1!+2!+3!+.....+n!.doc
1. 使用for循环
```c
#include <stdio.h>
int main() {
int n, s = 1;
printf("请输入n:");
scanf("%d", &n);
for(int i=1; i<=n; i++) {
int fact = 1;
for(int j=1; j<=i; j++) {
fact *= j;
}
s *= fact;
}
printf("s = %d\n", s);
return 0;
}
```
2. 使用while循环
```c
#include <stdio.h>
int main() {
int n, i = 1, s = 1;
printf("请输入n:");
scanf("%d", &n);
while(i <= n) {
int j = 1, fact = 1;
while(j <= i) {
fact *= j;
j++;
}
s *= fact;
i++;
}
printf("s = %d\n", s);
return 0;
}
```
3. 使用do-while循环
```c
#include <stdio.h>
int main() {
int n, i = 1, s = 1;
printf("请输入n:");
scanf("%d", &n);
do {
int j = 1, fact = 1;
do {
fact *= j;
j++;
} while(j <= i);
s *= fact;
i++;
} while(i <= n);
printf("s = %d\n", s);
return 0;
}
```
阅读全文