(섭씨와 화씨 간 변환) 다음 함수를 작성하여라.
변환 공식은 다음과 같다.
fahrenheit = (9.0 / 5) * celsius +32
celsius = (5.0 / 9) * (fahrenheit - 32)
(문제 출처 - C++로 시작하는 객체지향 프로그래밍 6.9)
#include <iostream>
#include <iomanip> //`setw()`, `setprecision()`을 사용하기 위함
using namespace std;
double celsiusToFahrenheit(double celsius)
{
return (9.0 / 5) * celsius + 32;
}
double FahrenheitToCelsius(double fahrenheit)
{
return (5.0 / 9) * (fahrenheit - 32);
}
int main()
{
cout << "Celsius" << setw(13) << "Fahrenheit" << setw(6) << "|" <<
setw(16) << "Fahrenheit" << setw(10) << "Celsius" << endl;
cout << "--------------------------------------------------" << endl;
double celsius = 40.0;
double fahrenheit = 120.0;
for (int i = 10; i > 0; celsius--, fahrenheit -= 10, i--) //증감식 범위
{
cout << fixed << setprecision(1) << celsius << setw(11) <<
celsiusToFahrenheit(celsius) << setw(11) << "|" << setw(11) <<
fahrenheit << setw(13);
cout << fixed << setprecision(2) <<
FahrenheitToCelsius(fahrenheit) << endl;
}
return 0;
}
setprecision()
은 출력되는 칸을 지정한다. 소수점은 반올림하여 출력하는데, 반올림을 원하지 않으면 앞에 fixed
를 작성한다. (부동소수점으로 만듦)
출력할 변수 앞에 작성한다.
setw()
은 괄호 안의 숫자만큼 공간을 확보한 뒤 문자를 출력한다.
setw()
직후에 출력하는 문자열의 가장 마지막 문자를 기준으로 공간을 확보한다.
ex) "Celsius" << setw(10) << "Fahrenheit"
을 작성하면 공백 출력 X
반복문의 증감식에서 i++
는 i = i + 1
을 의미한다.
2 이상 증가하는 증감식은 i = i + n
, 즉 i ±= n
으로 작성한다.
#include <iostream>
#include <iomanip>
using namespace std;
double celsiusToFahrenheit(double celsius)
{
return (9.0 / 5.0) * celsius + 32;
}
double fahrenheitToCelsius(double fahrenheit)
{
return (5.0 / 9) * (fahrenheit - 32);
}
int main()
{
cout << setw(12) << "Celsius" << setw(12) << "Fahrenheit";
cout << setw(12) << "|";
cout << setw(12) << "Fahrenheit" << setw(12) << "Celsius" << endl;
cout << "-----------------------------------------------------------"
<< endl;
double celsius = 40.0;
double farenheit = 120.0;
double ret_far, ret_cel;
for (int i = 1; i <= 10; celsius--, farenheit -= 10, i++)
{
ret_far = celsiusToFahrenheit(celsius);
ret_cel = fahrenheitToCelsius(farenheit);
cout << fixed << setprecision(1) << showpoint; // 소숫점 한자리
cout << setw(12) << celsius << setw(12) << ret_far;
cout << setw(12) << "|" << setw(12) << farenheit;
cout << fixed << setprecision(2) << showpoint; // 소숫점 두자리
cout << setw(12) << ret_cel << endl;
}
return 0;
}
함수를 호출할 때 ret_far, ret_cel
등의 변수를 사용하고setprecision
과 showpoint
를 함께 사용했다.
.