2014-09-29 2 views
1

사용자가 등변면 사다리꼴의 면적을 계산할 수있는 클래스 용 프로그램을 작성 중입니다. 그것은 13.5의 답변 발생한다 때 나는, 12.0의 답변을 얻을 것이다, 높이수학 방정식 결과가 표시 될 때 소수점 이하 자릿수가 사라짐

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를 들어, bottomLength 7, 3 : 여기 내 코드입니다. 아무도 내 코드가 잘못된 대답을 인쇄하고 .5를 인쇄하지 않는 이유를 알고 있습니까?

답변

3

문제의 근원은 "정수 구분"이라고 할 수 있습니다. Java에서 2 개의 정수를 나눌 경우 비 둥근 정수가됩니다.

아래에 여러 가지 방법으로 문제를 해결할 수 있습니다. 나는 당신이 정수가 아닌 값으로 공식을 사용할 수있게하는 첫 번째 방법을 선호한다. 아니 삼각형의 모든 길이는 Scanner#getDouble를 사용하고 당신에게 원하는 출력을 줄 것이다 double의에서 topLength, bottomLengthheight을 배치 정수 :


있습니다.

귀하의 코드는 다음과 같이 표시됩니다 :

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을 (를) 당신이 광고를 통해 파생하고있는 것으로 변환하십시오. ouble :

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

이러한 모든 옵션을 얻을 것입니다 :

이등변 사다리꼴의 면적은 13.5

+1

이러한 간단한 수정, 나는 거의도에 대한 바보가 된 기분 질문. 고마워요! – Kjc21793

+2

StackOverflow를 살펴보면 Integer Division 문제에 얽매여있는 사람들이 꽤 있습니다. 이제 알았어! 다행스럽게 도울 수있어! (당신이하고 싶은 것에 따라 업데이트를 보아라 - 더 쉬운 수정들) – blo0p3r

관련 문제