Java 数学公式结果在显示时丢失小数

Java 数学公式结果在显示时丢失小数,java,math,Java,Math,我正在为类编写一个程序,允许用户计算等腰梯形的面积。这是我的密码: 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 to

我正在为类编写一个程序,允许用户计算等腰梯形的面积。这是我的密码:

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);
   }
}

如果我输入,比如说,2代表topLength,7代表bottomLength,3代表height,我将得到12.0的答案,而结果应该是13.5。有人知道为什么我的代码打印出错误的答案而不打印.5吗?

问题的基础可以称为“整数除法”。在Java中,除以2个整数将得到一个非舍入整数

以下是解决您所遇到问题的多种方法。我更喜欢第一种方法,因为它允许您对非整数值使用公式。并非三角形的所有长度都是整数:)


使用并将
topLength
bottomLength
height
放入
double
s中,将获得所需的输出

然后,您的代码将如下所示:

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
s转换为双倍,并计算
trapArea
,如下所示:

double trapArea=((双)顶长+(双)底长)/2*((双)高);

或者,如果您愿意,也可以简单地将您要使用的
2
转换为双精度:

double trapArea=((顶部长度+底部长度)/2.0*(高度));

所有这些选项将产生:

等腰梯形的面积为:13.5


这么简单的修复,我甚至问都觉得自己很愚蠢。非常感谢你!如果你环顾一下StackOverflow,有相当多的人被整数除法的问题困住了。现在你知道了!很高兴我能帮忙!(请参阅更新-更简单的修复-取决于您想要执行的操作)