简体   繁体   中英

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

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:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM