Casting Int to Float

Hi,

I am trying to declare TestAvg as a int however, cast it as a float to show the decimal places.

1
2
3
4
5
6
7
8
9
10
int ProgramOne, ProgramTwo, ProgramThree, ProgramFour, ProgramFive, TestOne, TestTwo, ProgAvg, TestAvg, CourseAvg;


fin>>FirstName>>LastName>>ProgramOne>>ProgramTwo>>ProgramThree>>ProgramFour>>ProgramFive>>TestOne>>TestTwo;


//CALCULATIONS 
TestAvg= (float)(TestOne+TestTwo)/(2);

cout<<left<<fixed<<showpoint<<setprecision(2);


However it is still displaying as a integer.
If you want TestAvg to have decimal places make it a float (or double).
Last edited on
TestAvg is an int. You're calculating a float, but assiging it to an int.
The float calculation will be truncated on assignment.

Well I originally had it like this to provide decimal places

1
2
3
4
5
6
7
8
9
int ProgramOne, ProgramTwo, ProgramThree, ProgramFour, ProgramFive, TestOne, TestTwo;
float TestAvg;

TestAvg=(TestOne+TestTwo)/2;

//ALLOWS DECIMAL PLACES
cout<<left<<fixed<<showpoint<<setprecision(2);



But I guess that's not "casting" I was told by my professor I had to "cast my float" does that make any sense?

How to I calculate my int and assign the value to a float?
Last edited on
You still need the cast, otherwise the compiler is going to interpret the division as integer division. The divison operator has higher operator precedence than the assignment operator so you're going to do integer division even though the left lside is a float.
So for a final config it should look like this, correct?

1
2
3
4
5
6
7
8
9
10

int ProgramOne, ProgramTwo, ProgramThree, ProgramFour, ProgramFive, TestOne, TestTwo;
float TestAvg;

TestAvg= (float)(TestOne+TestTwo)/(2);

//ALLOWS DECIMAL PLACES
cout<<left<<fixed<<showpoint<<setprecision(2);

Last edited on
That should be fine. The cast has higher priority than the division.
Hum...well then what is the point of this statement? I think I'm missing the understanding of "Casting a float"


 
TestAvg= (float)(TestOne+TestTwo)/(2);


Why Not?

1
2
TestAvg= (TestOne+TestTwo)/(2);
Last edited on
TestOne and TestTwo are integers. You add them together you get an integer. You divide that integer by 2 you get an integer. eg. (5+4)/2 = 4, not 4.5
If you want the result to retan the fractional component, you have to cast it to a float before doing the division. (float)(5+4)/2 = 4.5
Yes,

So would I declare TestAvg as a float or as a Int?
Do you want the fractional component or not?
If not, then make it an int. As I said before, assignment to an int will drop the fractional component.
If you do want the fractional component, then you better make it a float since only a float will store the fractional component.
Topic archived. No new replies allowed.