java - 数学方程结果在显示时丢失小数点

标签 java math

我正在为类(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并将 topLengthbottomLengthheight 放在 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/

相关文章:

python - 如何在python中的另外两条线之间插入一条线

java - 如何使用 Dagger-2 延迟注入(inject)接口(interface)?

java - Liferay 输入日期格式

php - 返回任意数量项目的最小 X(可以包含 Y 项目)

python - 迭代具有特定总和的列表

Javascript - Math.random 改进

使用谷歌自定义搜索 API 的 Java 代码

java - 我可以在本地无线网络上制作安卓游戏吗?

java - 如何为简单的 Maven 应用程序配置 slf4j 以正确显示日志?

java - 固定线程池和大量任务的线程问题