简体   繁体   中英

error in pow from math.h

I am stuck with this error in C and just can't figure out what's going wrong. The following query forms an integral part of my code to increment the values exponentially in successive iterations. Here is the formula that I programmed:

I have commented the errors in the code.

#include <math.h>
#include <iostream>

int main()
{
    double maxMeshS = 0;
    double minMeshS = 0;

    cout << "enter max mesh size (m): ";
    cin >>maxMeshS;

    cout <<"\nenter min mesh size (m): ";
    cin >> minMeshS;

    double raise = maxMeshS/minMeshS; //Values used for run maxMeshS = .5
    double factor = 1/9;              //                    minMeshS = .005    

    double b = pow(raise,factor);
    cout << "b " << b << endl;  // The error happens here when I use above values
                               // b comes out to be 1 which should be 1.668100 instead
    double a = minMeshS/b;
    cout << "a " << a << endl;

    int x;
    cout << "enter x " ;
    cin >> x;

    double queryCube = a*pow(b,x);
    cout << queryCube << endl;
    return(0);
}

However when I use calculated values for the division maxMeshS/minMeshS ie 100 and 1/9 ie .11111 I obtain the right values for b = pow(100, .1111) = 1.66800 . Why is this happening?

Your factor is (int)1 / (int)9 which is (int)0; Almost anything raised to the zeroth power is one you could do something like this

double factor = 1/9.0; // make sure the 9 is a floating point

if I am not mistaken, you have to change the factor to

double factor = 1.0/9;

The issue is the fact that the compiler does treat 1/9 as an integer division, which results in 0. So you calculate the power of zero which is always 1.

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