Q1. 화씨(Fahrenhit)를 섭씨(Celcius)로 변환하는 코드를 완성하라. 섭씨를 구하는 식은 C = 5/9*(F-32) 이다.
A1. Math.round()
class Ex2_8 {
public static void main(String args[]) {
int fahrenhit = 100;
float celcius = Math.round(5/9f*(fahrenhit-32)*100)/100f;
// 100을 곱해준뒤 원하는 자리수가 나오도록 나눈다
System.out.println("f:"+fahrenhit);
System.out.println("c:"+celcius);
}
}
A2. (int)(+0.5)
class Ex2_8 {
public static void main(String args[]) {
int fahrenhit = 100;
float celcius = (int)((5/9f*(fahrenhit-32))*100 + 0.5)/100f;
// 0.5를 더해 반올림한 값을 구한다
System.out.println("f:"+fahrenhit);
System.out.println("c:"+celcius);
}
}
'Backend > Java' 카테고리의 다른 글
반복되는 음수값이 있는 총합 구하기 (0) | 2022.06.29 |
---|---|
랜덤 숫자 맞히기(do - while문) (0) | 2022.06.29 |
2차원 배열 연습 (0) | 2022.06.23 |
Singleton 패턴 (0) | 2022.06.22 |
[클래스와 객체] Date is Valid? (0) | 2022.06.21 |