首页 > 解决方案 > 每次返回双精度数组的元素时输出相同

问题描述

新手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;
}

}

标签: c++arraysdouble

解决方案


推荐阅读