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!!!!!!!!
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 >

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 >

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?