calc in function not working

1
2
3
4
5
6
7
8
float calcbavg(int hit,int ab)
{
    float ba;
    cout << hit << "\n" << ab << "\n";
    ba=(hit/ab);
    cout << setprecision(3) << ba <<"\n";
    return ba;
}    


i pass the right information into this function but only time right answer comes up is if you have the var hit and var ab at 1 and it prints out 1.000 else i get the result of .000 i know the right info is sent in as the cout statements show me what is passed to the function. I call the function with the following bavg=calcbavg(hits,atbats); bavg is a float. i also have tried it just using the formula in the main program with same results. any help would be appreciated. the formula is a basic formula for calc. a persons batting avg. of hits divided by at bats
Is this what you want?
ba=float(hit)/float(ab);
Those are conversions, not function calls.
question is i shouldn't have to do that right? the var are ints and would be entered as such not as floats. The only thing that is a float is the answer. And it does result in an answer but it is always .000 except if you enter 1 & for the ints. if you for example enter 1 for hit and 3 for ab the answer should show .333 not .000. Why would i have to convert the ints in the formula to floats unless i am missing something off what should be a simple formula?
The compiler always converts operands to the more accurate type if they are of different types. In this case, both operands are ints. The compiler simply performs integer division on them and then converts the result to float and assigns ba to it:
/(int,int)
float(int)
float=float

The compiler is by design not smart enough to look at the left-hand operand of the assignment operator and see whether it should perform the conversion implicitly. There are many cases where it's desirable to divide two ints and assign the result to a float.
Topic archived. No new replies allowed.