JAVA

이것이 자바다 3장 확인 문제 풀이 (연산자)

Adev 2022. 10. 2. 00:01

1. 연산자와 연산식 - 연산에 사용되는 표시나 기호를 연산자(operator)라고 하고, 연산의 과정을 기술한 것을 연산식(expressions)이라고 부른다.
답 : 3
연산식은 하나 이상의 값을 산출할 수 없다.

 


2. 단항연산자
답 : 11+20 = 31

 


3. 삼항연산자, 논리부정 연산자
답 : 가

 


4. 
답 : pencils/students, penciles%students

package verify;
public class Exercise04 {
	public static void main(String[] args) {
		int pencils = 534;
		int students = 30;
		
		//학생 한 명이 가지는 연필 수
		int pencilsPerStudent = ( pencils / students ); 
		System.out.println(pencilsPerStudent);
		
		//남은 연필 수
		int pencilsLeft = ( pencils % students );
		System.out.println(pencilsLeft);
	}
}

 


5.
답 :  value/100*100

package verify;
public class Exercise05 {
	public static void main(String[] args) {
		int value = 356;
		System.out.println(   value / 100 * 100    );
	}
}



6.
답 : (lengthTop + lengthBottom) * height / 2.0 = 52.5

package verify;
public class Exercise06 {
	public static void main(String[] args) {
		int lengthTop = 5;
		int lengthBottom = 10;
		int height = 7;
		double area = (   ((lengthTop + lengthBottom) * height / 2.0));
		System.out.println(area);
	}
}

//(lengthTop + lengthBottom) * height / 2 = 52.0 (X)

산술 연산자의 특징은 피연산자들의 타입이 동일하지 않을 경우 정해진 규칙을 사용해서 피연산자들의 타입을 일치시킨 후 연산을 수행한다. long을 제외한 정수 타입 연산은 int 타입으로 산출되고, 피연산자 중 하나라도 실수 타입(float, double)이면 실수 타입으로 산출된다. 정수 타입 연산 결과가 int 타입으로 나오는 이유는 자바 가상 기계(JVM)가 기본적으로 32비트 단위로 계산하기 때문이다. 따라서 소수점을 가진 수를 산출 결과로 얻고 싶다면 피연산자 중 최소한 하나는 실수 타입이어야 한다.
 


7. 
답: true, false

 


8. 입력값의 NaN 검사
답 : Double.isNaN(z)

package verify;
public class Exercise08 {
	public static void main(String[] args) {
	  double x = 5.0;
		double y = 0.0;
		
		double z = 5 % y;
		
		if( Double.isNaN(z) ) {
			System.out.println("0.0으로 나눌 수 없습니다.");
		} else {
			double result = z + 10;
			System.out.println("결과: " + result);
		}
	}
}