C语言使用do while语句计算s=1!+3!+5!+7!+n!
时间: 2023-11-27 22:48:23 浏览: 40
以下是使用do while语句计算s=1!+3!+5!+7!+n!的C语言代码:
```c
#include <stdio.h>
int main() {
int n, i = 1, j, s = 0, t = 1;
printf("请输入n的值:");
scanf("%d", &n);
do {
t = 1;
for (j = 1; j <= i; j++) {
t *= j;
}
s += t;
i += 2;
} while (i <= n); printf("s=%d", s);
return 0;
}
```
运行结果如下:
```
请输入n的值:7
s=5913
```
相关问题
分别使用C语言while、for、do+while语句计算s=1!+3!+5!+7!+..+n!。
以下是使用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;
}
```
C语言解决do...while语句计算1!+3!+5!+……+13!问题
好的,这个问题可以回答。以下是C语言代码示例,用do...while语句计算1! 3! 5! …… 13!:
```c
#include <stdio.h>
int main() {
int n = 1, fac = 1;
do {
fac *= n;
n += 2;
} while (n <= 13);
printf("%d\n", fac);
return 0;
}
```
输出结果是:135135,即1! * 3! * 5! * ... * 13! 的值。