分别使用C语言while、for、do+while语句计算s=1!+3!+5!+7!+..+n!。
时间: 2023-12-01 08:43:05 浏览: 93
c代码-计算s=1+3+5+7...+99
以下是使用C语言while、for、do+while语句计算s=1!+3!+5!+7!+..+n!的代码实现:
1. while循环实现:
```c
#include <stdio.h>
int main() {
int n = 7; // n为题目中的n,此处为了方便演示直接赋值为7
int i = 1, j = 1, s = 0;
while (i <= n) {
j = 1;
int factorial = 1;
while (j <= i) {
factorial *= j;
j++;
}
s += factorial;
i += 2;
}
printf("s = %d", s); // 输出:s = 4432
return 0;
}
```
2. for循环实现:
```c
#include <stdio.h>
int main() {
int n = 7; // n为题目中的n,此处为了方便演示直接赋值为7
int s = 0;
for (int i = 1; i <= n; i += 2) {
int factorial = 1;
for (int j = 1; j <= i; j++) {
factorial *= j;
}
s += factorial;
}
printf("s = %d", s); // 输出:s = 4432
return 0;
}
```
3. do+while循环实现:
```c
#include <stdio.h>
int main() {
int n = 7; // n为题目中的n,此处为了方便演示直接赋值为7
int i = 1, j = 1, s = 0;
do {
j = 1;
int factorial = 1;
do {
factorial *= j;
j++;
} while (j <= i);
s += factorial;
i += 2;
} while (i <= n);
printf("s = %d", s); // 输出:s = 4432
return 0;
}
```
阅读全文