Question

enter image description here

I need to calculate the value of e^x. The loop is infinity and should stop when i get the precision 0.001, but i do not know how to get this precision.

float exp(float x){
    float ex=1,precision=0.000,powX=1.0,fat=1.0;
    int partInt;
    int i,j;
    for(i=1; precision!= 0.001; i++){
        for(j=1; j<=i; j++){
            powX *= x;
            fat *=j;
        }
        ex += powX/fat;
        partInt = ex;             // like a cast to integer
        precision= ex - partInt; // get the precision
        //printf("%f %f %f %f\n",powX,fat,precision,ex);
        powX = fat = 1.0;
    }
    return ex;
}


int main(){
    printf("%f",exp(2));
    return 0;
}
Était-ce utile?

La solution

You could use a double prev to keep track of the result produced by the previous iteration. Stop when abs(prev - ex) < precision.

Autres conseils

In your code, precision is always 0 when checked, because you assign ex's value to partInt, and then subtract them.

You can store each loop's result in a variable, and then compare it to the next loop's result. When their difference is less than 0.001, stop the loop.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top