需要计算收敛到π的级数方程
Need to calculate series equation converging to π
第一次编程时,我必须编写一个计算级数方程的程序(n!)^2×2^n+1/(2n+1)!,n是用户输入的术语的数量。
我已经得到了用户输入n的地方,我只得到了这个数字的答案。
如何获得从0到用户输入的所有答案的总和?
#include <iostream>
#include<cmath>
using namespace std;
int main()
{
double i,n,factorial,factorial2,n2,a;
a = 1;
cout<<"Enter # of terms:";
cin>>n;
for (i = 0; i <= n; i++)
if (i == 0)
factorial = 1;
else
factorial = factorial * i;
factorial = pow(factorial,2)*pow(2,n+1);
n2 = 2*n+a;
for (i = 0; i <= n2; i++)
if (i == 0)
factorial2 = 1;
else
factorial2 = factorial2 * i;
factorial = factorial/factorial2;
cout<<factorial<<endl;
system("PAUSE");
}
这是我的评论中的代码,所有这些都是可读的。。。
#include <iostream>
#include <cmath>
int factorial(int n)
{
return n <= 1 ? 1 : factorial(n - 1) * n;
}
或者,如果您发现阶乘函数令人困惑,SlySherZ建议使用这种初学者友好的替代方法(您不希望同时实现)。
int factorial(int n)
{
if (n <= 1)
return 1;
return factorial(n - 1) * n;
}
正在继续。。。
double f(double n)
{
return std::pow(fact(n),2) * std::pow(2, n) + 1 / factorial(2 * n + 1);
}
int main()
{
double n, total = 0;
while (std::cin >> n)
total += f(n);
std::cout << "total " << total << 'n';
}
您有两个选项:
- 使用一个循环来遍历每个n
-
制作递归函数:
// In pseudocode term (n){ if ( n < 0 ) return 0; // calculate y for this n; return y + term( n - 1 ); }
递归函数(假设你熟悉函数)是一个调用自己来解决问题的函数。例如,n!=(n-1)!*n.您可以使用这个简单的事实创建一个阶乘函数f(n),它返回n*f(n-1),除非n是1(在这种情况下返回1)。
我将开发第一个选项:
// I assumed your code is working and that factorial holds the values you want to sum.
// If that's not the case, I believe you can use it to solve your problem anyway
#include <iostream>
#include<cmath>
using namespace std;
int main() {
double n, total = 0;
cout << "Enter # of terms:";
cin >> n;
while (n >= 0) {
double i, factorial, factorial2, n2, a;
a = 1;
for (i = 0; i <= n; i++) {
if (i == 0)
factorial = 1;
else
factorial = factorial * i;
}
factorial = pow(factorial, 2)*pow(2, n + 1);
n2 = 2 * n + a;
for (i = 0; i <= n2; i++) {
if (i == 0)
factorial2 = 1;
else
factorial2 = factorial2 * i;
factorial = factorial / factorial2;
}
total += factorial;
n--;
}
cout << total << endl;
}
希望它能有所帮助:D
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 递归函数计算序列中的平方和(并输出过程)
- (C++)分析树以计算返回错误值的简单算术表达式
- 我的字符计数代码计算错误.为什么
- 在计算中使用二的幂有多有利可图
- 如何计算文件中的"columns"数?
- 计算排序向量的向量中唯一值的计数
- 如何使用 std::累积在 C++ 中计算总和立方体
- 使用Qt C++计算类似Git的SHA1哈希
- OpenCV C++.快速计算混淆矩阵
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- C++如何计算用户输入的数字中的偶数位数
- 如何计算数据类型的范围,例如int
- 类似枚举的计算常量
- 计算每个节点的树高,帮助我解释这个代码解决方案
- 正弦级数方程计算不正确
- 快速计算三角方程 c++ 解的方法
- 需要计算收敛到π的级数方程
- 我必须重新计算每个函数的私有变量方程吗?
- 用c++编写一个程序来计算所有可能的方程