分别使用while、for、do+while+语句计算s=1!+3!+5!+7!+…++n!。
时间: 2023-11-28 13:46:02 浏览: 84
以下是使用while、for、do-while语句计算s=1!+3!+5!+7!+…++n!的代码实现:
1. 使用while语句:
```python
n = int(input("请输入一个正整数:"))
s = 0
i = 1
while i <= n:
j = 1
p = 1
while j <= i:
p *= j
j += 1
s += p
i += 2
print("s的值为:", s)
```
2. 使用for语句:
```python
n = int(input("请输入一个正整数:"))
s = 0
for i in range(1, n+1, 2):
p = 1
for j in range(1, i+1):
p *= j
s += p
print("s的值为:", s)
```
3. 使用do-while语句:
```python
n = int(input("请输入一个正整数:"))
s = 0
i = 1
while True:
j = 1
p = 1
while j <= i:
p *= j
j += 1
s += p
i += 2
if i > n:
break
print("s的值为:", s)
```
相关问题
c++分别使用while、for、do+while语句计算s=1!+3!+5!+7!+n!
以下是使用while、for、do+while语句计算s=1!+3!+5!+7!+n!的C++代码实现:
1. while语句实现:
```c++
#include <iostream>
using namespace std;
int main() {
int n = 7;
int i = 1;
int s = 0;
int fac = 1;
while (i <= n) {
fac = 1;
int j = 1;
while (j <= i) {
fac *= j;
j++;
}
s += fac;
i += 2;
}
cout << "s = " << s << endl;
return 0;
}
```
2. for语句实现:
```c++
#include <iostream>
using namespace std;
int main() {
int n = 7;
int s = 0;
for (int i = 1; i <= n; i += 2) {
int fac = 1;
for (int j = 1; j <= i; j++) {
fac *= j;
}
s += fac;
}
cout << "s = " << s << endl;
return 0;
}
```
3. do+while语句实现:
```c++
#include <iostream>
using namespace std;
int main() {
int n = 7;
int i = 1;
int s = 0;
do {
int fac = 1;
int j = 1;
do {
fac *= j;
j++;
} while (j <= i);
s += fac;
i += 2;
} while (i <= n);
cout << "s = " << s << endl;
return 0;
}
```
(2)分别使用while、for、do+while语句计算s=1!+3!+5!+7!+n!
可以使用以下代码来计算s=1!+3!+5!+7!+n!:
```
int n = 7; // 假设n为7
int s = 0;
int i = 1;
int j = 1;
while (i <= n) {
j = 1;
int factorial = 1;
while (j <= i) {
factorial *= j;
j += 2;
}
s += factorial;
i += 2;
}
System.out.println("s=" + s);
```
```
int n = 7; // 假设n为7
int s = 0;
for (int i = 1; i <= n; i += 2) {
int factorial = 1;
for (int j = 1; j <= i; j += 2) {
factorial *= j;
}
s += factorial;
}
System.out.println("s=" + s);
```
```
int n = 7; // 假设n为7
int s = 0;
int i = 1;
do {
int factorial = 1;
int j = 1;
do {
factorial *= j;
j += 2;
} while (j <= i);
s += factorial;
i += 2;
} while (i <= n);
System.out.println("s=" + s);
```
其中,第一个while循环中的j每次增加2,是因为只需要计算奇数的阶乘;第二个for循环中的i每次增加2,同样是因为只需要计算奇数的阶乘;第一个do-while循环中的j每次增加2,是因为只需要计算奇数的阶乘,而i每次增加2,同样是因为只需要计算奇数的阶乘。
阅读全文