[BOJ] (b4) 1008_A/B

강신현·2022년 1월 15일
0
post-thumbnail

문제 링크

try1

#include <iostream>

using namespace std;

int main(){

    int A, B;
    float ans;

    cin >> A >> B;

    ans = (float)A/B;
    cout << ans << endl;


    return 0;
}

-> 0.333333

출력 오차 범위 조건을 못맞춰 오답.

try2

✅ cout.precision(n);

출력할 실수 전체 자리수를 n으로 표현하는 메소드

✅ cout << fixed;

precision에서 넘겨준 값 만큼 고정 소수점 표기로 전환하여 출력하는 메소드

✅ cout.unsetf(ios::fixed);

cout << fixed; 을 다시 해제해서 실수 전체의 출력 범위를 설정

#include <iostream>

using namespace std;

int main(){

    int A, B;

    cin >> A >> B;

    cout.precision(12);
    cout << fixed;

    cout << (float)A / B << endl;
    
    // cout.unsetf(ios::fixed);

    return 0;
}

-> 0.333333343267

float과 double의 차이로 인한 오답.

try3

✅ double vs float

  1. C++ 표준이 자료형의 최소크기만 정해놨기 때문에 개인 컴퓨터에서 float의 크기와 서버의 float크기가 다를 수 있고, 이 경우는 오버플로우가 발생할 수 있다.

  2. double은 15-16개의 10진수를, float은 7개의 10진수를 표현한다. 그러므로 일반적으로 double은 float보다 2배 정도 더 정확하다고 한다.

결론 : 🔥 double을 애용하자!

#include <iostream>

using namespace std;

int main(){

    int A, B;

    cin >> A >> B;

    cout.precision(12);
    cout << fixed;

    cout << (double)A / B << endl;

    return 0;
}

-> 0.333333333333

정답.

출처
https://kdjcomputer.tistory.com/49

profile
땅콩의 모험 (server)

0개의 댓글