[英]Unexpected output in a java program
我編寫了以下java代碼,其中A三角形的面積為0
。 此錯誤輸出的原因可能是什么?
package methodoverrideoverload;
import java.io.*;
import java.util.*;
class Figure_Area {
int dima;
int dimb;
Figure_Area()
{
}
Figure_Area(int i, int j)
{
dima=i;
dimb=j;
}
void cal_area()
{
System.out.println("Area is undefined!!");
}
}
class Figure_Area_Tri extends Figure_Area {
Figure_Area_Tri(int i, int j)
{
super(i,j);
}
void cal_area()
{
System.out.println("The area of the Triangle is "+((1/2)*dima*dimb));
}
}
class Figure_Area_Rec extends Figure_Area {
Figure_Area_Rec(int i, int j)
{
super(i,j);
}
void cal_area()
{
System.out.println("The area of the Rectangle is "+ dima*dimb);
}
}
class Figure_Area_Cir extends Figure_Area {
double pi=3.14;
Figure_Area_Cir(int i)
{
super.dima=i;
}
void cal_area()
{
System.out.println("The area of the Circle is "+ (pi*dima*dima));
}
}
class findArea {
public static void main(String args[]) throws IOException
{
System.out.println("<<-MENU-->>");
System.out.println("Enter the figure you want to know the area of->");
System.out.println("Press 1 for Triangle");
System.out.println("Press 2 for Rectangle");
System.out.println("Press 3 for Circle");
System.out.println("Press 4 to Exit");
System.out.println("Enter your choice->");
Scanner sc=new Scanner(System.in);
int ch=sc.nextInt();
switch(ch)
{
case 1:
System.out.println("Enter Height->");
int h=sc.nextInt();
System.out.println("Enter Base->");
int b=sc.nextInt();
Figure_Area_Tri tri=new Figure_Area_Tri(h,b);
tri.cal_area();
break;
case 2:
System.out.println("Enter Length->");
int len=sc.nextInt();
System.out.println("Enter Breadth->");
int bre=sc.nextInt();
Figure_Area_Rec rec=new Figure_Area_Rec(len,bre);
rec.cal_area();
break;
case 3:
System.out.println("Enter Radius->");
int rad=sc.nextInt();
Figure_Area_Cir cir=new Figure_Area_Cir(rad);
cir.cal_area();
break;
case 4:
break;
default:
System.out.println("Sorry! Invalid Choice");
}
}
}
我已經在調試模式下檢查了代碼,發現dima
和dimb
的值被設置為輸入值,但是以某種方式,area函數很可能無法給出正確的結果。
例如,對於整數變量,java使用整數數學
1/2==0
為了解決這個問題,請使用雙重數學
1.0/2==0.5
1d也可以代替1.0
所以你的情況
(1.0/2)*dima*dimb
只要其中一個變量是雙精度變量,然后應用雙精度數學運算(請注意,當方程式包含多個“部分”時,每個部分都必須有一個雙精度變量)。
請注意,僅強制轉換為double( (double)(1/2)*dima*dimb
)並不能解決問題,因為細節已經在強制轉換為double的點上丟失了,因為
(double)(1/2)*dima*dimb
(double)(0)*(dima*dimb)
(double)(0)
0.0
您正在使用1/2等於0
您需要使用雙精度,所以1.0 / 2.0 = 0.5
嘗試將double或float用作1/2。
如果您使用整數,則它將為0,因為沒有整數等值為0.5。
您可以寫例如1/2f
或1/2d
或查看其他答案:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.