easy java help please?

Chau

Senior member
May 23, 2001
712
4
71
say i have 3 numbers, all 3 are ints... such as x = 1, y = 2, z = 3

and i want to calculate the average of the ints by performinag FLOATing point division...

could i just set a variable like

float average;

and then do float = (1+2+4)/3 and have the result be the average in a float type? that doesn't seem to work...would i have to take in the 3 variables as float and not int to do that?

thanks!
 

yoda291

Diamond Member
Aug 11, 2001
5,079
0
0
there really should be a homework forum I think

You need to cast your integers into floats.

It's been ages since I've had to do a cast in java, but I think you could get away with

float avg;
avg = (float)((x+y+z)/3);

but don't hold me to that.
 

Silex

Golden Member
Nov 24, 2001
1,829
0
0
These guys are all right. But in general terms, you need to make sure that all variables and contants on the right side of the equation are floating point, and then you need to make sure that your left side results in a floating type. The funny thing is how with the other way around (integers), you don't need to specify it if you input a floating point number, because java just castrates the decimal (hah). so you can float each number in the average, the average of the sums, or the average of the sums over the integer 3. To be as accurate as poissble, you want to covert to floating point as early on in the equation as you can.