Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What should I do so that "nan" doesn't show up in console?

My teacher gave this homework. Basically I have two numbers, a and b. I have to show to console answer of this formula for every ‘a’ number added h=(b-a)/10 but in console I see just nan. How can I solve this error?
My code is:

#include <iostream>
#include <math.h>
using namespace std;
double s(double x){
    long f = 1;
    long double anw=1;
    for(int k=1;k<=100;k++){
        f=k*f;
         anw=((pow((x-1),k)*pow(log(3),k))/f)+anw;
    }
    return anw;
}
int main(){
    double a=0.2, b=0.8, h;
    h=(b-a)/10;
    for(double x=a; x<=b ;x+=h){
        cout<<"s(x)="<<s(x)<<endl;
    }
    return 0;
}

Sorry for my bad English!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You get a signed integer overflow in f=k*f; so I suggest that you make f a double:

double s(double x){
    double f = 1;              // double
    long double anw=1;
    for(int k=1;k<=100;k++){
        f = k * f;             // or else you get a signed integer overflow here
        // f *= k;             // a simpler way of writing the above
        anw=((pow((x-1),k)*pow(log(3),k))/f)+anw;
    }
    return anw;
}

Another note: Include the C++ header cmath instead of the C header math.h.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading