Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
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
Tags
more
Archives
Today
Total
관리 메뉴

Hennie

[백준] 1008번 : A/B (JAVA) 본문

BaekJoon/01. 입출력과 사칙연산

[백준] 1008번 : A/B (JAVA)

헨니 2021. 4. 9. 21:10

 

QUESTION

www.acmicpc.net/problem/1008

 

1008번: A/B

두 정수 A와 B를 입력받은 다음, A/B를 출력하는 프로그램을 작성하시오.

www.acmicpc.net

 

ANSWER

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int a = scan.nextInt();
		int b = scan.nextInt();
		double result = (double)a/b;
		System.out.println(String.format("%.9f", result));
	}
}

 

RESULT

 

MEMO

double result = (double)(a/b);

위와 같이 적을 경우 a, b 모두 int형이기 때문에 int형 / int형 = int형이 나오게 되고,

이 정수값을 실수형으로 변환하기 때문에 원하는 값이 출력되지 않는다.

double result = (double)a/b;

따라서 위와 같이 a를 실수형으로 변환한 후 연산을 해주면 우리가 원하는 대로 소수점 아래 값까지 계산되어 나오게 된다.

String.format("%.9f", result);

result 값을 소수점 아래 10번째 자리에서 반올림하여 소수점 아래 9번째 자리까지 출력한다.