why is the answer not showing up?

I am doing a code in c++ where I am supposed to be finding the series and I build the function for the series myself yet and I call the function I don't find my answer here is my code

#include <iostream>
#include <cmath>
using namespace std;
double harmonicSeries(int n);
int main() {
    int n;
    cout << "Enter n" << endl;
    cin >> n;
    harmonicSeries(n);
}
double harmonicSeries(int n) {
    for (int i = 1; i <= n; i++) {
        float s;
        float sum = 0.0;
        s = 1 / n;
        sum += s;
        return sum;
    }
}

I will be thankful for any help

1 answer

  • answered 2021-05-05 10:27 Yatin arora

    See I have made the changes in your code,this works fine in this finding numbers and adding to get their sum.You should use return outside the function and basically harmonic series is of form 1/n which can be any float number or double number so I use s as double and i has float(which by this).

    s=1/i(double=1/float,gets converted to double)

    #include <iostream>
    #include <cmath>
    using namespace std;
    double harmonicSeries(int n);
    int main() {
    int n;
    cout << "Enter n" << endl;
    cin >> n;
    cout<<harmonicSeries(n);
     }
    double harmonicSeries(int n) {
    double sum=0.00;
    double s;
    for (float i = 1; i <= n; i++) {
        s = 1 / i;
        sum += s;
    }
    return sum;
    }
    

    If you find anything wrong do ask for sure:)