Correct answer before return, wrong after return

I have been working for hours, but with no luck.

I am using standard c, calling a very simple method and returning the correct value, but after returning, the value is completely wrong.

call:

     //declare the gross and ficaTax variables
    double gross;
    double ficaTax;

    //calculate the gross and the ficaTax
    gross = calcGross(payRate, hours); printf("%f\n", gross); //DELETE

      

Method:

double calcGross(double rate, double hours){

    double gross;

    //if the person didn't work more than 40 hours  
    if(hours <= 40.0){
            gross = hours * rate;
    }

    //if the person did work more than 40 hours
    else{
            gross = 40.0 * rate + ((hours - 40.0) * rate * 1.5);
    }

    printf("%f \t", gross);
    return gross;
}

      

I am printing the values ​​inside and out of the method to try and solve it, but I cannot figure it out. Here's the result:

(correct) (incorrect, after return)

529.600000, -858993459.000000

1371.522500, 171798692.000000

100.000000, 0.000000

1515.710000, 171798692.000000

977.255000, 1030792150.000000

5631.360000, 687194767.000000

7502.400000, 1717986918.000000

4335.106000, 584115553.000000

1924.181500, -618475291.000000

683.084000, 137438953.000000

1348.424000, 755914245.000000

1369.200000, -858993460.000000

529.600000, -858993459.000000

4441.522500, -1030792152.000000

100.000000, 0.000000

1882.710000, 171798692.000000

My only guess was that my double postback was too long to fit the length of the double, but I saved it in the double preposition and printed it correctly. If so, I couldn't figure out how to fix it. My other guess was that I am printing out the wrong post-return, but I am printing it the same way.

I am using Linux and with gcc compiler if it matters. Any help would be greatly appreciated. I've been trying to fix this seemingly simple issue for hours.

+3


source to share


3 answers


The problem is that you didn't give a declaration or prototype for the function calcgross()

before calling it in the first example.

Without seeing the function declaration / prototype, the C compiler will assume it is returning int

, not double

, so things go horribly wrong.

Place the following line somewhere before you call the function (ideally in the header that you include):



double calcGross(double rate, double hours);

      

Using a -Wall

compiler option will give you the following warning about this:

test.c:73:5: warning: implicit declaration of function 'calcGross' [-Wimplicit-function-declaration]

      

+4


source


The most likely problem is that you did not declare it calcGross

before using it, in which case the compiler will use the default return type ( int

). Try to put a definition calcGross()

before using it.



+4


source


Silly, subtle mistake. Use "printf ("% lf ", gross)" in both places and I bet the problem goes away :)

-1


source







All Articles