error in pow from math.h

421 views Asked by At

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?

2

There are 2 answers

5
McKay On

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
0
michael81 On

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.