![[백준 / BOJ] 1008번 A/B (C++, Python)](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FCvg0u%2FbtrK90gTt9Y%2FAj6J69I7xUxtWbDg4jju01%2Fimg.jpg)
[백준 / BOJ] 1008번 A/B (C++, Python)◎ 자료구조와 알고리즘/백준(BOJ) 문제풀이2022. 9. 1. 19:10
반응형
링크 : https://www.acmicpc.net/problem/1008
1008번: A/B
두 정수 A와 B를 입력받은 다음, A/B를 출력하는 프로그램을 작성하시오.
www.acmicpc.net
문제

문제 풀이
정답과 출력값의 절대오차 또는 상대오차가 10^-9 이하라는 조건 때문에 생각해 볼 여지가 있는 문제다.
"10-9 이하의 오차를 허용한다는 말은 꼭 소수 9번째 자리까지만 출력하라는 뜻이 아니다."
이 문구가 왜 있는 것일까? 우선 float와 double형을 이해해야 한다.
float형은 메모리 크기가 32bit이고, double형은 메모리 크기가 64bit이다. 이러한 크기 차이 때문에 표현가능한 소수점 이하 자리수가 float형은 6자리, double형은 15자리이다. 따라서 위 조건에 따라 float형은 오차범위를 넘어선 오차가 생길 가능성이 있다는 것을 알 수 있다.
즉, 이 문제는 double형을 사용해야 하는 문제다. (long double형도 당연히 가능하다.)
아 물론 파이썬은 double형이 존재하지 않는다!
C++ 상세 풀이
C++ 풀이 펼쳐보기
precision을 사용해 15자리까지만 출력하도록 하면 된다.
double A, B;
std::cin >> A >> B;
std::cout.precision(15);
std::cout << A / B;
Python 상세 풀이
Python 풀이 펼쳐보기
파이썬은 형 변환이 자동으로 이루어지기 때문에 그냥 나눗셈을 해도 정답 처리된다.
if __name__ == "__main__":
A, B = map(int, input().split())
print(A / B)
코드 전문
C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
void init() { | |
std::ios_base::sync_with_stdio(false); | |
std::cin.tie(nullptr); | |
std::cout.tie(nullptr); | |
} | |
int main() { | |
init(); | |
double A, B; | |
std::cin >> A >> B; | |
std::cout.precision(15); | |
std::cout << A / B; | |
return 0; | |
} |
Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if __name__ == "__main__": | |
A, B = map(int, input().split()) | |
print(A / B) |
소감
반응형
'◎ 자료구조와 알고리즘 > 백준(BOJ) 문제풀이' 카테고리의 다른 글
[백준 / BOJ] 10926번 ??! (C++, Python) (0) | 2022.09.01 |
---|---|
[백준 / BOJ] 10869번 사칙연산 (C++, Python) (0) | 2022.09.01 |
[백준 / BOJ] 10998번 AxB (C++, Python) (0) | 2022.09.01 |
[백준 / BOJ] 1001번 A-B (C++, Python) (0) | 2022.09.01 |
[백준 / BOJ] 1000번 A+B (C++, Python) (부제 : map(int, input().split())에 대하여) (0) | 2022.08.31 |
@Reo :: 코드 아카이브
자기계발 블로그