변수 a와 b의 사칙연산(+, -, *, /) 결과를 출력하라.

 

조건1. int a = 10, b = 4;

조건2. System.out.printf(); 이용

조건3. 나눗셈의 경우 int 타입과 float 타입 두 가지 모두 출력

 

 

 

public class P097_OperatorEx5 {
	public static void main(String[] args) {
		int a = 10;
		int b = 4;
		System.out.printf("%d + %d = %d%n", a, b, a + b);		// 10 + 4 = 14
		System.out.printf("%d - %d = %d%n", a, b, a - b);		// 10 - 4 = 6
		System.out.printf("%d * %d = %d%n", a, b, a * b);		// 10 * 4 = 40
		System.out.printf("%d / %d = %d%n", a, b, a / b);		// 10 / 4 = 2 (값 소실)
		System.out.printf("%d / %f = %f%n", a, (float)b, a/ (float)b);	// 10 / 4.000000 = 2.500000
	}
}

 

 

 

 

 

 

 

세 수의 평균을 구해 소수 둘째자리까지 출력하라.

 

조건1. int score1 = 70, score2 = 70, score3 = 60;

조건2. 사칙연산으로 식을 구해 System.out.println();으로 출력

조건3. 66.67이 아닌 66.66이 출력되게 하라. 

조건4. 적절한 크기(scale) 변경과 형변환을 이용하라.

 

 

 

▼ 나의 풀이

public class P097_Operator_Assignment {
	public static void main(String[] args) {
		int score1 = 70;
		int score2 = 70;
		int score3 = 60;
        
		float aa = (float)(score1+score2+score3)/3*100;	// 6666.6665
		int bb = (int)aa;						// 6666
		float cc = (float)(bb);					// 6666.0
		System.out.println(cc/100);				// 66.66
    }
}

 

- 값의 크기(scale)을 바꾸는 개념을 생각해 낸 것은 좋았으나

- 형변환을 위해 만든 변수 aa, bb, cc의 경우

  가독성을 위해 좀 더 의미를 파악할 수 있는 이름으로 사용하는 것이 좋겠다.

  (예. avg = average)

- 데이터 타입을 바꾸기 위해 너무 풀어썼다.

  산술 변환 규칙을 확실히 파악하여 불필요한 코드를 줄여야 한다.

 

 

 

▼ 선생님 조언

		int sum = score1 + score2 + score3;
		double avg = sum * 100 / 3 / 100d;
		System.out.println(avg);			// 66.66

- 익숙해질 때까지 변수를 필요한 만큼 만들어 풀어쓰는 것은 좋은 방법이다.

- 형변환 연산자(double)를 쓰는 방법이 틀린 것은 절대 아니다.

  바꾸려고 하는 데이터 타입의 값(100d)을 연산해주어

  자동 형변환(산술 변환) 규칙에 따라 불필요한 코드를 줄일 수 있다.

  (두 피연산자의 타입이 다르면 보다 큰 타입으로 일치)

 

		System.out.println(sum * 100);			// 20000
		System.out.println(sum * 100 / 3 /100d);	// 6666
		System.out.println(sum * 100 / 3 /100d);	// 200
		System.out.println(sum * 100 / 3 /100d);	// 66.66

double avg = sum * 100 / 3 /100d;

문장을 이해하기 위해 부분별 출력값을 확인해보았다.

 

 

 

▼ 다른 학생 풀이

		int sum = score1 + score2 + score3;
		double avg = sum * 100 / 3 /100d;
		System.out.printf("%.2f", avg);		// 66.67

- System.out.printf():로 출력한다면

  원하는 소수점(또는 자릿수)까지 출력하게 할 수 있다고 한다.

- 이것은 특정 자릿수 표현을 위해 반올림을 하기 때문에

  이번 문제에서 원하는 값(66.66)은 얻을 수 없었다.