[C++] 5주차 과제 리뷰

yeohn·2022년 11월 11일
0

2022-2 C++ 과제 리뷰

목록 보기
5/10

문제

(섭씨와 화씨 간 변환) 다음 함수를 작성하여라.

변환 공식은 다음과 같다.
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 등의 변수를 사용하고setprecisionshowpoint를 함께 사용했다.


코드에 대한 교수님 코멘트

.

0개의 댓글