我写了以下程序:
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
问题在于,对于三角形肋骨的每个合法值,我都会在屏幕上显示 area 值0.0。
为什么?我做的一切似乎都很好..不是吗?!
日Thnx
答案 0 :(得分:3)
您的s
变量是在整数空间默认值中计算的,您需要使其中一个操作数浮动以避免舍入错误,例如:
float s = (a+b+c) / (float) 2;
您也可以考虑构建更容易来阅读if-clauses,例如
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)
答案 1 :(得分:1)
更改
float s = (a+b+c) / 2 ;
到
float s = (float)(a+b+c) / 2 ;
应该有用。
答案 2 :(得分:0)
你正在进行整数运算。您需要使用nextFloat()
或nextDouble()
代替nextInt()
。
答案 3 :(得分: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
答案 4 :(得分:0)
使用Windows Vista
和SUN JDK 1.6_b18
eclipse 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
答案 5 :(得分:0)
尝试更改:
float s = (a+b+c) / 2;
为:
float s = (float)(a+b+c) / (float)2;
前者正在进行整数除法,这可能会导致一些舍入错误。