gpt4 book ai didi

java - 为什么我无法打印值(value)?

转载 作者:行者123 更新时间:2023-12-01 19:19:14 25 4
gpt4 key购买 nike

我编写了以下程序:

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。

这是为什么呢?我所做的一切似乎都很好..不是吗?!

谢谢

最佳答案

您的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)

关于java - 为什么我无法打印值(value)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5146832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com