2014-09-29 63 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