c++分别使用while、for、do+while语句计算s=1!+3!+5!+7!+n!
时间: 2023-11-28 17:46:30 浏览: 88
以下是使用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;
}
```
阅读全文