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

Time:12-05

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!

CodePudding user response:

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.

  • Related