求1+1/2+1/3+1/4+1/5的和。用C++写出代码
时间: 2023-10-03 14:05:06 浏览: 104
#include<stdio.h>
int main()
{
float sum=0;
for(int i=1;i<=5;i++) //循环5次
{
sum+=1.0/i; //每次加上1/i的值
}
printf("1/1+1/2+1/3+1/4+1/5的和为:%f",sum);
return 0;
}
相关问题
用c++写出1+1/1!+1/2!+1/3!+…+1/n!
这个问题涉及到计算阶乘和累加的操作。你可以使用循环和递归两种方式来实现。下面是使用循环的示例代码:
```cpp
#include <iostream>
double factorial(int n) {
double result = 1.0;
for (int i = 1; i <= n; ++i) {
result *= i;
}
return result;
}
double calculateSum(int n) {
double sum = 0.0;
for (int i = 0; i <= n; ++i) {
sum += 1.0 / factorial(i);
}
return sum;
}
int main() {
int n;
std::cout << "请输入n的值:";
std::cin >> n;
double result = calculateSum(n);
std::cout << "结果为:" << result << std::endl;
return 0;
}
```
这段代码中,`factorial`函数用于计算阶乘,`calculateSum`函数用于计算累加和。在`main`函数中,用户输入一个整数n,然后调用`calculateSum`函数计算结果并输出。
递归调用求1!+2!+……+n!使用c++代码写出
以下是使用C++实现递归调用求1!+2!+……+n!的代码:
```cpp
#include <iostream>
using namespace std;
// 求阶乘的函数
int factorial(int n) {
if (n == 1) { // 递归头
return 1;
} else { // 递归体
return n * factorial(n - 1);
}
}
// 求1!+2!+...+n!的函数
int sumFactorial(int n) {
if (n == 1) { // 递归头
return 1;
} else { // 递归体
return factorial(n) + sumFactorial(n - 1);
}
}
int main() {
int n = 5;
int sum = sumFactorial(n);
cout << "1!+2!+...+" << n << "!的结果为:" << sum << endl;
return 0;
}
```
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)