2011-02-28 285 views
0

我寫了下面的程序:爲什麼我不能打印價值?

import java.util.Scanner ; 

public class Triangle 
{ 
    public static void main (String [] args) 
    { 
     Scanner scan = new Scanner (System.in) ; // new object named "scan" 

     // Next lines scan ribs values into a,b,c parameters 
     System.out.println ("Please enter first rib value : " ) ; 
     int a = scan.nextInt() ; 
     System.out.println ("Please enter second rib value : " ) ; 
     int b = scan.nextInt() ; 
     System.out.println ("Please enter third rib value : " ) ; 
     int c = scan.nextInt() ; 
     if (! ((a >= 1) && (b>=1) && (c>=1))) 
      System.out.println ("One or more of the ribs value is negative !!\nPlease enter a positive value ONLY ! " ) ;  
     else if (! ((a <= b+c) && (b <= a+c) && (c <= a+b))) 
      System.out.println ("Error !\n\nOne rib can not be bigger than the two others ! " ) ;  
     else 
     { 
      float s = (a+b+c)/2 ; 
      double area = Math.sqrt(s * (s-a) * (s-b) * (s-c)) ; 
      float perimeter = s*2 ; 
      System.out.println ("Perimeter of the triangle is: "+perimeter+"\n\nArea of the triangle is: "+area) ;  
     }// end of else 
     }//end of method main 
    } //end of class Triangle 

的問題是,我在屏幕上得到區域值0.0爲三角形的肋骨的每一個法律價值。

這是爲什麼?我做了一切似乎是好的..不是嗎?!

日Thnx

+0

對於輸入2,2,2我得到了'三角形的周長是:6.0 三角形的面積是:1.7320508075688772' – 2011-02-28 19:57:02

回答

3

s變量是在整數空間默認計算,你需要做一個操作數浮動,以避免舍入誤差,如:

float s = (a+b+c)/(float) 2; 

您也可以考慮構建更容易讀取if子句,例如,

if (! ((a >= 1) && (b>=1) && (c>=1))) 

if (a <= 0 || b <= 0 || c <= 0) 

如果你正在尋找創建Equilateral三角形第二if語句可以被轉換:

else if (! ((a <= b+c) && (b <= a+c) && (c <= a+b))) 

else if (a != b || b != c) 
+0

沒有幫助... 1,2,3給出:面積0. – Batman 2011-02-28 20:31:00

+0

由於很多其他人表示,該計劃*確實*起作用。確保你正在運行最新的源代碼,而不是soem緩存副本。另外,你是否運行oracle/sun java版本? – 2011-02-28 20:33:16

+0

你應該寫'2.0f'! – 2011-02-28 21:57:41

0

你做的整數運算。您需要使用nextFloat()nextDouble()而不是nextInt()

0

這似乎工作......可能是您使用的IDE?

macbook:java cem$ vi Triangle.java 
macbook:java cem$ javac Triangle.java 
macbook:java cem$ java Triangle 
Please enter first rib value : 
3 
Please enter second rib value : 
4 
Please enter third rib value : 
5 
Perimeter of the triangle is: 12.0 

Area of the triangle is: 6.0 
+0

3,4,5作品。嘗試輸入像.. 1,2,3 – Batman 2011-02-28 20:28:51

+0

的MacBook:JAVA CEM $ java的三角 請輸入第一肋值:請輸入第二肋值:請輸入第三肋值:周長三角形的是:6.0 三角形的面積爲:0.0 – 2011-02-28 20:31:27

+1

具有面1,2和3 *的三角形的面積爲零。 – 2011-02-28 20:31:44

0

Windows Vista正常工作與SUN JDK 1.6_b18eclipse 3.6 RCP

Please enter first rib value : 
5 
Please enter second rib value : 
4 
Please enter third rib value : 
3 
Perimeter of the triangle is: 12.0 

Area of the triangle is: 6.0 
0

嘗試改變:

float s = (a+b+c)/2; 

到:

float s = (float)(a+b+c)/(float)2; 

的前者正在做整數除法,這可能會導致你一些舍入誤差。

+1

你應該寫'2.0f'! – 2011-02-28 20:41:04

1

更改

float s = (a+b+c)/2 ; 

float s = (float)(a+b+c)/2 ; 

應該工作。