3

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?

Arne Mertz
  • 22,733
  • 2
  • 43
  • 86
akash_c
  • 173
  • 1
  • 2
  • 9
  • Not that important here, but you should try pick up the habit of always using `std::pow` from `cmath` instead of the C version from `math.h`. `std::pow` includes some important optimizations for integer exponents while C's `pow` uses `double` exponents no matter what (there is no function overloading in C). – Benjamin Bannier Aug 26 '13 at 15:06

2 Answers2

9

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
McKay
  • 11,801
  • 5
  • 46
  • 74
6

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.

michael81
  • 206
  • 2
  • 8