더 많이 실패하기

자바의정석 연습문제 풀이 6장 6-4 본문

자바/자바의정석-연습문제

자바의정석 연습문제 풀이 6장 6-4

김발자~ 2022. 9. 22. 01:32
반응형

자바의 정석 3판 연습문제 풀이

 

연습문제 파일은 아래 링크에서 다운받을 수 있다

https://github.com/castello/javajungsuk3/tree/master/%EC%97%B0%EC%8A%B5%EB%AC%B8%EC%A0%9C%ED%92%80%EC%9D%B4

 

GitHub - castello/javajungsuk3: soure codes and ppt files of javajungsuk 3rd edition

soure codes and ppt files of javajungsuk 3rd edition - GitHub - castello/javajungsuk3: soure codes and ppt files of javajungsuk 3rd edition

github.com

 

 

http://www.yes24.com/Product/Goods/24259565

 

Java의 정석 - YES24

최근 7년동안 자바 분야의 베스트 셀러 1위를 지켜온 `자바의 정석`의 최신판. 저자가 카페에서 12년간 직접 독자들에게 답변을 해오면서 초보자가 어려워하는 부분을 잘 파악하고 쓴 책. 뿐만 아

www.yes24.com

자바의 정석 저자 남궁성 님이 직접 올려주신 문제다

 


챕터6은 총 24문제로 구성되어 있다


6-4


 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class Practice_6_3 {
    public static void main(String[] args) {
        Student s = new Student();
        s.name = "홍길동";
        s.ban = 1;
        s.no = 1;
        s.kor = 100;
        s.eng = 60;
        s.math = 76;
        
        System.out.println("이름:"+s.name);
        System.out.println("총점:"+s.gotTotal());
        System.out.println("평균:"+s.getAverage());
    }
}
 
class Student{
    String name;
    int ban;
    int no;
    int kor;
    int eng;
    int math;
    
    int gotTotal() {
        return kor+eng+math;
    }
    
    float getAverage() {
        return (int)((kor+eng+math)/3f*10+0.5)/10f;
    }
}
cs

 

getAverage() 함수 중 소수점 둘째자리에서 반올림하게 만드는 과정이 조금 복잡할 수 있다

(문제에서 println을 사용했기 때문에 printf로 소수점 자리를 정해줄 수도 없다)

 

 

차례대로 보자면

1. kor+eng+math / 3 은 int 값으로 단순히 78.0이 출력된다

 

2. 그래서 첫 번째로 float타입으로 나누어 소수 자리를 모두 출력할 수 있게 만든다

kor+eng+math / 3f 는 78.666664

 

3. 10을 곱해 소수의 첫째자리를 1의자리로 만든다

kor+eng+math / 3f * 10 = 786.66664

 

4. 0.5를 더해 반올림한 것과 같은 효과를 준다 (0.5 미만이면 앞자리가 그대로 유지, 0.5 이상이면 앞자리 +1)

kor+eng+math / 3f * 10 + 0.5 = 787.16664

 

5. int로 형변환하여 소수점을 버린다

(int) (kor+eng+math / 3f * 10 + 0.5) = 787

 

6. 다시 10으로 나눠 본래 자리를 찾게 만든다

(int) (kor+eng+math / 3f * 10 + 0.5) / 10 = 78

 

7. int라서 소수점 자리가 버려지므로 f를 붙인다

(int) (kor+eng+math / 3f * 10 + 0.5) / 10f = 78.7

 


 

반응형
Comments