알고리즘/기초
화씨를 섭씨로 변환하는 코드
leegeonwoo
2023. 8. 6. 14:09
public class Main {
public static void main(String[] args) {
int fahrenheit = 100;
float celcius = (int)(5/9f * (fahrenheit-32) * 100 + 0.5)/100f;
System.out.println(fahrenheit);
System.out.println(celcius);
}
}
화씨를 섭씨로 바꾸는 공식은 '5/9f * (fahrenheit - 32)'이다.
1. 5/9의 연산은 0으로 나오기때문에 피연산자 한 곳을 float나 double로 지정해줘야 실수형태의 결과를 얻을수 있다.
2. 소수점 셋째자리에서 반올림을 해준다.
-값에 100을 곱하고 0.5를 더해준다.
3777.778 + 0.5 ->3778.278
결과를 int타입으로 변환하면 소수점은 버려지고 3778이되고 이 값을 100f로 나누어 주면 결과를 섭씨온도를 얻을 수 있다.
728x90