2011-02-28 289 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 ; 

应该工作。