数学方程式结果在显示时会丢失小数

时间:2014-09-29 22:31:34

标签: 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 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);
   }
}

如果我输入say,2为topLength,7为bottomLength,3为高度,我将得到12.0的答案,当它应该得到13.5的答案。有谁知道为什么我的代码打印错误答案而不打印.5?

1 个答案:

答案 0 :(得分:3)

问题的基础可以称为"整数分部"。在Java中,除以2个整数将产生非舍入整数。

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


使用Scanner#getDouble并在topLength中放置bottomLengthheightdouble将为您提供所需的输出。

您的代码将如下所示:

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转换成双打,然后计算你的trapArea

double trapArea = (((double)topLength + (double)bottomLength) / 2 * ((double)height));

或者甚至很简单,如果你愿意的话,将2转换为双倍:

double trapArea = ((topLength + bottomLength) / 2.0 * (height));

所有这些选项都会产生:

  

等腰梯形的面积为:13.5