hi guys am kinda new to the language i made this simple program about Fibonacci
and the program works fine but there is strange behavior when i try to get the average number
public class fibonacci {
/**
* @param args
*/
public static int fibonaccifun(int number)
{
int firstvar=1;
int secondvar=0,total=0,sum=0;
for(int i=0;i<number;i++)
{
total =firstvar+secondvar;
System.out.println(total);
firstvar=secondvar;
secondvar=total;
sum+=total;
}
return sum;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
float aver= (float) ( fibonacci.fibonaccifun(5)/5);
System.out.println(aver);
………………………………
when i try
float aver= (float) ( fibonacci.fibonaccifun(5))/5; the result is 2.4 which is the correct value ,however when i do this
float aver= ((float) fibonacci.fibonaccifun(5)/5); the average =2.0;
i dont know why it do this so can anyone helps me explaining this ,thx guys.
because in the second case
fibonacci.fibonaccifun(5)/5goes to 2, as both the result of
fibonaccifunand 5 are ints, THEN you cast to float. (If you divide 2 ints, the result is an int, and ints obviously can’t have decimals)In the first case
(float) ( fibonacci.fibonaccifun(5))makes the result of
fibonaccifuna float, THEN you do the division.