2014-09-29 38 views
1

我正在编写一个程序,它允许用户计算等腰梯形的面积。这里是我的代码:数学公式结果在显示时丢失小数

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的高度,我会得到的12.0答案,当它应该导致13.5答案。有谁知道为什么我的代码打印错误的答案,而不是打印.5?

回答

3

该问题的基础可以被称为“整数部门”。在Java中,除2个整数将产生一个非舍入整数。

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


使用Scanner#getDouble,并把topLengthbottomLengthheightdouble旨意给你想要的输出。

那么您的代码将是这样的:

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 = (((double)topLength + (double)bottomLength)/2 * ((double)height)); 

甚至很简单,如果你愿意的话,可以将你正在分配的2转换成广告ouble:

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

所有这些选项将产生:

等腰梯形的面积为:13.5

+1

这样一个简单的修复,我几乎觉得愚蠢甚至问。非常感谢你! – Kjc21793 2014-09-29 22:47:13

+2

如果你环顾一下StackOverflow,有不少人会被Integer Division问题困住。现在你知道了!很高兴我能帮上忙! (请参阅更新 - 更简单的修复 - 取决于您想要做什么) – blo0p3r 2014-09-29 22:48:24