SKSDUD

[소소한개념] float과 double의 차이는 무엇일까? 본문

프로그래밍/개발공부

[소소한개념] float과 double의 차이는 무엇일까?

NYinJP 2023. 6. 25. 17:18

 

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        // 정수 배열로 입력받기
        // 배열 모두 합한 값 찾기
        int sum=0;
        int [] score = new int[num];
        for(int i=0;i<num;i++){
            score[i] = sc.nextInt();
            sum+=score[i];
        }
        // 배열 정렬해서 최대값 찾기
        Arrays.sort(score);
        int max = score[num - 1];
        // 합한 값을 이용해 수학 공식 이용해서 값 얻기
        float newScore = (sum*100.0)/(max*num);

        System.out.println(newScore);

    }​
public class main {
    public static void main(String[] args) {

        float f = 10f;
        System.out.println(f);

        double d = 10;
        System.out.println(d);

        System.out.println(f+10);
        System.out.println(d+10);
        System.out.println(f/3);
        System.out.println(d/3);

    }
}

결과

10.0
10.0
20.0
20.0
3.3333333
3.3333333333333335

 


 

do it 알고리즘 코딩테스트 책으로 공부하고 있다. 한 달 안에 끝내는 게 목표이다!

매일 3시간 씩 볼 예정

 

그나저나 갈 길이 멀다!

 

자바 실수형을 저장하는 자료형에는 float(4byte)과 double(8byte)이 있는데

유효자릿수가 다르다. float은 7 자릿수까지 double은 15-16 자릿수까지 보장한다.

 

근데 코드에서 오류(Incompatible types. Found: 'double', required: 'float')가 났다! 이유는

 

Java에서 실수형 상수 100.0의  자료형을 double로 저장하기 때문이다. 기본 자료형이 double!

위의 코드에서 볼 수 있듯이 다른 자료형끼리의 계산은 큰 자료형을 따라가므로 결과가 double로 나오게 되는데

double을 float 자료형 변수에 저장하려고 하니 에러가 발생한 것이다!!

double로 바꾸거나 캐스팅 연산자를 사용해 (float) double -> float으로 변환해 float 변수에 저장하면 된다.

 

실수형 상수의 기본 자료형은 Double!! 알고나니 별거 아닌데 모르니까 당황스럽구나!