我正在为类(class)编写一个程序,它允许用户计算等腰梯形的面积。这是我的代码:
import java.util.Scanner;
import java.lang.Math;
public class CSCD210Lab2
{
public static void main (String [] args)
{
Scanner mathInput = new Scanner(System.in);
//declare variables
int topLength, bottomLength, height;
//Get user input
System.out.print("Please enter length of the top of isosceles trapezoid: ") ;
topLength = mathInput.nextInt() ;
mathInput.nextLine() ;
System.out.print("Please enter length of the bottom of isosceles trapezoid: ") ;
bottomLength = mathInput.nextInt() ;
mathInput.nextLine() ;
System.out.print("Please enter height of Isosceles trapezoid: ") ;
height = mathInput.nextInt() ;
mathInput.nextLine() ;
double trapArea = ((topLength + bottomLength)/2*(height));
System.out.println();
System.out.printf("The area of the isosceles trapezoid is: "+trapArea);
}
}
如果我输入 topLength 为 2,bottomLength 为 7,高度为 3,我将得到 12.0 的答案,而结果应该是 13.5。有谁知道为什么我的代码打印出错误答案而不打印 .5?
最佳答案
问题的基础可以称为“整数除法”。在 Java 中,除以 2 个整数将得到一个非四舍五入的整数。
以下是解决您遇到的问题的多种方法。我更喜欢第一种方法,因为它允许您使用具有非整数值的公式。并非所有三角形的长度都是整数:)
使用 Scanner#getDouble并将 topLength
、bottomLength
和 height
放在 double
中将为您提供所需的输出。
您的代码将如下所示:
public static void main(String[] args) {
Scanner mathInput = new Scanner(System.in);
// declare variables
double topLength, bottomLength, height;
// Get user input
System.out.print("Please enter length of the top of isosceles trapezoid: ");
topLength = mathInput.nextDouble();
mathInput.nextLine();
System.out.print("Please enter length of the bottom of isosceles trapezoid: ");
bottomLength = mathInput.nextDouble();
mathInput.nextLine();
System.out.print("Please enter height of Isosceles trapezoid: ");
height = mathInput.nextDouble();
mathInput.nextLine();
double trapArea = ((topLength + bottomLength) / 2 * (height));
System.out.println();
System.out.printf("The area of the isosceles trapezoid is: " + trapArea);
}
您还可以将您的 int
转换为 double 并计算您的 trapArea
:
double trapArea = (((double)topLength + (double)bottomLength) / 2 * ((double)height));
或者更简单,如果你愿意,将你分配的 2
转换为 double :
double trapArea = ((topLength + bottomLength) / 2.0 * (height));
所有这些选项都会产生:
The area of the isosceles trapezoid is: 13.5
关于java - 数学方程结果在显示时丢失小数点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26109968/