c++ - 每次返回双精度数组的元素时输出相同
问题描述
新手C学生在这里。我正在尝试编写一个名为 seriesSum 的函数,它接受一个整数参数并按照下面的模式返回和 n 个数字。
// seriesSum(1) => 1 = "1.00"
// seriesSum(2) => 1 + 1/4 = "1.25"
// seriesSum(5) => 1 + 1/4 + 1/7 + 1/10 + 1/13 = "1.57"
简单地将 n 项相加,每个项的分母每项增加 3。如果 n = 0,程序应将总和返回到小数点后两位并返回 0.00。n 只会被赋予自然数(正整数和 0)。
但是,每当我输入 n 的值时,每次都会得到 1.00 作为输出。我不想将整个逻辑重新写入我的程序;我只是希望有人能指出谬误以及为什么我每次都得到 1.00。我的代码如下。提前致谢。
#include <iostream>
#include <string>
using namespace std;
double seriesSum(int n);
int main()
{
int n = 2;
seriesSum(n);
}
// write a function which returns the sum of following series up to nth
// parameter.
// need to round the answer to 2 decimal places and return as a string
// if the given value is 0, must return 0.00
// will only be given natural numbers as arguments
double seriesSum(int n)
{
double nDouble[n];
if (n == 0)
{
nDouble[0] = 0;
cout.precision(2);
cout << fixed << nDouble[0] << endl;
return nDouble[0];
}
else
{
nDouble[0] = 1;
int i;
for (i = 1; i < n; i++)
{
nDouble[i] = (1) / (1 + (3 * i));
}
double sum = 0;
int j;
for (j = 0; j < n; j++)
{
sum += nDouble[j];
}
cout.precision(2); // setting to 2 decimal places
cout << fixed << sum << endl; // not sure what fixed means but it works
return sum;
}
}
解决方案
推荐阅读
- flutter - 如何在自定义 FlatButton 的以下代码中使边框“更厚”?
- html - 为什么 VUEJS 风格的 z-index 不起作用?
- angular - 服务返回对象数组而不是对象
- php - 使用其他 XML 源扩展 SimpleXML 类
- python - 是否可以从 python 3.8 中的不同目录导入包中的所有模块?
- python - 与 sql alchemy 的烧瓶关系 - 没有这样的表错误
- wordpress - 如何从路径中删除 WordPress 页面?
- python-3.x - 在while循环中比较两个变量时遇到问题
- python - 带有 Python 库的 Excel 中可用的 COM 加载项的拉取列表
- javascript - 在javascript中存储键值对