What is the error in this program?

class FindArea

{

public static void main(String args[])

{

float radius=7.0f;

float area=(22/7)*(radius)*(radius);

System.out.println(area);

}

}

When i execute the above program i am getting output as 147.0 why it is happening? I dont understand.....

Actually it should come...154!!!!!!!!

[354 byte] By [ale_ramesha] at [2007-11-27 0:48:01]
# 1

class FindArea

{

public static void main(String args[])

{

float radius=7.0f;

float area=(22/7)*(radius)*(radius); // problem here

System.out.println(area);

}

}

(22/7) return an int which is 3, but i think you want a float

rym82a at 2007-7-11 23:16:43 > top of Java-index,Java Essentials,New To Java...
# 2
BTW Pi is declared as a static variable in the Math class. Use that for more accurate results.
floundera at 2007-7-11 23:16:43 > top of Java-index,Java Essentials,New To Java...
# 3
So how should i modify this program to get correct answer.........?
ale_ramesha at 2007-7-11 23:16:43 > top of Java-index,Java Essentials,New To Java...
# 4
A. Use your brainB. Failing that replace 22/7 with Math.PI. Not rocket science.
floundera at 2007-7-11 23:16:43 > top of Java-index,Java Essentials,New To Java...
# 5
In a stupid way, explicitly telling it's a floatIn a smarter way, use Math.PI http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Math.html#PI
rym82a at 2007-7-11 23:16:43 > top of Java-index,Java Essentials,New To Java...
# 6

When you divide one int by another the result is "truncated" (the decimal part is

thrown away). If you don't want this to happen you have to tell the compiler to

treat your integer as a double (or float). This is done in the first two cases, but not

the third.public class IntOrDouble {

public static void main(String[] args) {

// prints 15.0

double answer1 = ((double)3 / 2) * 10;

System.out.println("answer 1 = " + answer1);

// prints 15.0

double answer2 = (3.0 / 2) * 10;

System.out.println("answer 2 = " + answer2);

// prints 10.0 because 3/2 is 1

double answer3 = (3 / 2) * 10;

System.out.println("answer 3 = " + answer3);

}

}

Test: so, what will (double)(3/2)*10 print?

pbrockway2a at 2007-7-11 23:16:43 > top of Java-index,Java Essentials,New To Java...