/*
두 수 바꾸기 - 포인터
두 수를 입력받아 값을 바꾸어 출력하는 프로그램을 작성하시오
단, 포인터를 이용하시오.
Input
두 값은 정수이다.
Output
두 수를 바꾸어 출력한다.
Sample Input
100 30
Sample Output
30 100
*/
#include <iostream>
void swap(int *a, int * b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int main(void)
{
int a = 0, b = 0;
std::cin >> a >> b;
swap(&a, &b);
std::cout << a << " " << b;
}
/*
단어 뒤집기 - 포인터
단어를 입력받아 단어를 뒤집어 출력하는 프로그램을 작성하시오
단, 포인터를 이용하시오.
Input
단어는 공백을 포함하지 않는다.
Output
포인터를 이용하여 단어를 뒤집어 출력한다.
Sample Input
silent
Sample Output
tnelis
*/
#include <iostream>
#include <string>
using namespace std;
int main(void) {
string str;
cin >> str;
char *s = &str[str.size()-1];
while(cout << s[0])
if(--s < &str[0])
break;
return 0;
}
/*
도형의 넓이와 둘레 구하기
직사각형을 나타내는 Rectangle 클래스와 원을 나타내는 Circle 클래스를 작성하시오.
이 두 클래스는 넓이를 구하는 기능과 둘레를 구하는 기능을 지녀야 한다.
다음에 제공되는 main 함수와 출력 결과를 통해서 요구되는 Rectangle 클래스와 Circle클래스를 작성하시오.
※ 직사각형의 넓이 : 가로 × 세로 둘레 : (가로 + 세로) × 2
※ 원의 넓이 : 반지름2 × 3.14 둘레 : 2 × 반지름 × 3.14
int main(void)
{
int x, y, r;
cin >> x >> y >> r; //(가로, 세로, 반지름을 입력받음)
Rectangle rec(x, y); //Rectangle rec(가로길이, 세로길이)
cout << rec.GetArea() << endl;
cout << rec.GetGirth() << endl;
Circle cir(r); //Circle cir(원의 반지름)
cout << cir.GetArea() << endl;
cout << cir.GetGirth() << endl;
return 0;
}
Input
가로, 세로, 반지름 순으로 입력 받는다.
Output
사각형의 넓이, 사각형의 둘레, 원의 넓이, 원의 둘레 순으로 출력한다.
원의 넓이와 둘레는 소수점 둘째자리 까지 출력한다.
소수점 첫번째 자리까지 출력하기
cout.setf(ios::fixed, ios::floatfield);
cout.precision(2);
Sample Input
3 4 5
Sample Output
12
14
78.50
31.40
*/
#include <iostream>
using namespace std;
#define pi 3.14
class Rectangle {
private:
int width;
int height;
public:
Rectangle( int w, int h );
int GetArea( );
int GetGirth( );
};
Rectangle::Rectangle( int w = 0, int h = 0 )
{
this->width = w;
this->height = h;
}
int Rectangle::GetArea( )
{
return (this->width * this->height);
}
int Rectangle::GetGirth( )
{
return (this->width * 2 + this->height * 2 );
}
class Circle {
private:
double radius;
public:
Circle( int r);
double GetArea( );
double GetGirth( );
};
Circle::Circle( int r = 0 )
{
this->radius = (double)r;
}
double Circle::GetArea( )
{
return ( pi * this->radius * this->radius );
}
double Circle::GetGirth( )
{
return (2.0 * pi * this->radius);
}
int main(void)
{
int x, y, r;
cin >> x >> y >> r; //(가로, 세로, 반지름을 입력받음)
Rectangle rec(x, y); //Rectangle rec(가로길이, 세로길이)
cout << rec.GetArea() << endl;
cout << rec.GetGirth() << endl;
cout.setf(ios::fixed, ios::floatfield);
cout.precision(2);
Circle cir(r); //Circle cir(원의 반지름)
cout << cir.GetArea() << endl;
cout << cir.GetGirth() << endl;
return 0;
}
/*
시, 분, 초 출력하기
시(hour), 분(minute), 초(second) 정보를 지닐 수 있는 Time 클래스를 작성하시오.
이 클래스는 멤버 변수가 지니고 있는 데이터를 적절히 출력하는 기능을 지녀야 한다.
출력방식은 두 가지로 제공한다. 하나는 [시, 분, 초]의 형식을 띄며, 또 하나는 초 단위로 계산한 출력 결과를 보여준다.
제시되는 main 함수와 출력결과를 참조하시오.
int main()
{
int hour, min, sec;
int choice;
cin >> choice;
if(choice == 1)
{
cin >> hour;
Time time(hour);
time.ShowTime();
time.ShowTimeinSec();
}
else if(choice == 2)
{
cin >> hour >> min;
Time time(hour, min);
time.ShowTime();
time.ShowTimeinSec();
}
else if(choice == 3)
{
cin >> hour >> min >> sec;
Time time(hour, min, sec);
time.ShowTime();
time.ShowTimeinSec();
}
return 0;
}
Input
입력 형식을 입력 받는다.
1. 시
2. 시, 분
3. 시, 분, 초
형식에 맞게 시, 분, 초를 입력받는다.
Output
시(h), 분(m), 초(s)를 단위와 함께 출력한다. 없는 단위는 0으로 출력한다.
다음, 입력받은 수를 초단위로 환산하여 출력한다.
Sample Input1
1
10
Sample Output1
10h 0m 0s
36000s
Sample Input2
2
5 10
Sample Output2
5h 10m 0s
18600s
Sample Input3
3
7 30 20
Sample Output3
7h 30m 20s
27020s
*/
#include <iostream>
using namespace std;
class Time {
private:
int hour, min, second;
public:
Time(int hour, int min, int sec);
void ShowTime( );
void ShowTimeinSec();
};
Time::Time(int hour = 0, int min = 0, int sec = 0) {
this->hour = hour;
this->min = min;
this->second = sec;
}
void Time::ShowTime( ) {
cout << this->hour << "h " << this->min << "m " << this->second << "s" << endl;
}
void Time::ShowTimeinSec( ) {
cout << this->hour * 3600 + this->min * 60 + this->second << "s" << endl;
}
int main(void)
{
int hour, min, sec;
int choice;
cin >> choice;
if(choice == 1)
{
cin >> hour;
Time time(hour);
time.ShowTime();
time.ShowTimeinSec();
}
else if(choice == 2)
{
cin >> hour >> min;
Time time(hour, min);
time.ShowTime();
time.ShowTimeinSec();
}
else if(choice == 3)
{
cin >> hour >> min >> sec;
Time time(hour, min, sec);
time.ShowTime();
time.ShowTimeinSec();
}
return 0;
}
/*
Student_info 맴버 함수 다루기
Student_info 객체를 다루기 위해서는, 프로그래머들이 사용할 수 있는 인터페이스를 정의해야 합니다.
레코드 하나를 읽고(read), 전체 성적(grade)을 계산하는 프로그램을 작성하세요. S
tudent_info 구조체는 이렇게 정의 됩니다.
struct Student_info {
string name;
double midterm,
final; vector< double > homework;
istream& read(istream&) // 추가된 맴버함수
double grade() const; //추가된 맴버함수
}
맴버 함수들은 입력 스트림으로부터 한 레코드를 읽어드리고(read), 모든 Student_info 객체에 대해 최종 성적(grade)을 계산합니다.
grade의 선언 시 사용한 const는 grade 함수가 Student_info 객체의 데이터 맴버를 전혀 변경하지 않을 것이라는 것을 나타냅니다.
전체 성적의 계산방식은 0.2 * 중간점수 + 0.4 * 기말점수 + 0.4 * 과제 입니다.
과제를 계산 할때 4.1.1절의 중앙값 찾기를 통해 중앙값을 찾아서 계산해 줍니다.
단, C++의 형식에 맞추어 COUT을 이용해 출력하셔야 합니다.
EOF처리는 while(입력) 와 같이 하시면 됩니다.
참고 : 맴버 함수의 이름은 보통의 read, grade가 아니라 Student_info::read, Student_info::grade입니다.
중앙값을 계산할때 나오는 sort함수는 algorithm헤더에 정의 되어있습니다.
INPUT
학생들의 성적을 입력합니다.
4.2.2절의 read함수를 이용해 이름과 시험점수를 입력받고,
4.1.3절의 read_hw함수를 이용해 과제점수를 입력받습니다.
입력순서는 이름 >> 중간시험점수 >> 기말시험점수 >> 과제 입니다.
참고 : read_hw함수는 read함수에 포함되어 있습니다.
과제점수를 여러개 입력할때 EOF처리는 while(입력)입니다.
학생의 성적과 과제 점수 입력을 마치고난뒤 EOF처리를 두 번 해줘야 프로그램의 결과가 출력됩니다.
OUTPUT
학생들의 이름과 최종성적이 출력 됩니다.
최종성적은 소수점 첫째자리까지 출력합니다.
출력이 끝나면 개행처리를 해줍니다.
입력 예제 1
joo 100 70 10 5 4 1 0
park 100 60 10 5 4 1 0
lee 87 32 3 2 1 8 8
출력 예제 1
joo 49.6
park 45.6
lee 31.4
*/
#include <iostream>
#include <istream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct Student_info {
string name;
double midterm, final;
vector<double> homework;
double grade() const;
istream& read(istream& in);
istream& read_hw( istream& in);
};
// 0.2 * 중간점수 + 0.4 * 기말점수 + 0.4 * 과제
double Student_info::grade() const {
vector<double>::size_type size = this->homework.size();
vector<double>::size_type mid = size / 2;
double hw_mid = (size%2 == 0) ? (this->homework[mid] + this->homework[mid-1]) / 2 : this->homework[mid];
return ((0.2 * this->midterm) + (0.4 * this->final) + (0.4 * hw_mid));
}
istream& Student_info::read(istream& in)
{
if(!(in >> this->name)) // 이름에서 eof가 들어오면 학생 입력 종료 처리
return in;
in >> this->midterm;
in >> this->final;
read_hw( in );
return in;
}
istream& Student_info::read_hw( istream& in)
{
if(in) {
double x;
while(in >> x)
this->homework.push_back(x);
}
sort(this->homework.begin(), this->homework.end());
in.clear();
return in;
}
int main(void)
{
vector<Student_info> student_list;
while(1) {
Student_info st;
st.read(cin);
if(cin.eof()) // 만약 eof bit 가 설정이 되어 있으면 학생 입력 종료
break;
student_list.push_back(st);
}
cout.setf( ios::fixed, ios::floatfield );
cout.precision( 1 );
for(vector<Student_info>::iterator i = student_list.begin(); i != student_list.end(); i++ )
cout << i->name << ' ' << i->grade() << endl;
return 0;
}
substr()함수 사용법
s = "abcdef";
s1 = s.substr(0, 3); //s1에 s의 0번째 부터 3개의 문자를 넣는다.
cout << s1 << endl;
출력 : abc
Input
입력종료 문자가(EOF)가 입력되면 종료된다.
Output
출력형식은 다음과 같다.
area code 063
이름1 전화번호1
이름2 전화번호2
...
not area code 063
이름1 전화번호1
이름2 전화번호2
...
출력조건은 다음과 같다.
1) 지역번호가 "063"이면 area code 063에, 그렇지 않다면 not area code 063에 출력한다.
2) 출력 순서는 area code 063, not area code 063순이다.
3) 이름은 가장 긴 사람에게 맞춘다.
4) area code 063, not area code 063은 해당하는 사람이 없을 경우에는 출력하지 않는다.
Sample Input1
Kim 063-000-0000
Park 062-000-0001
HongGilDong 063-000-0002
Sample Output1
area code 063
HongGilDong 063-000-0002
Kim 063-000-0000
not area code 063
Park 062-000-0001
Sample Input2
Jo 062-000-0003
HongGilDong 062-000-0002
Sample Output2
not area code 063
HongGilDong 062-000-0002
Jo 062-000-0003
접기|
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
#define UINT unsigned int
// 전화번호 구조체
typedef struct _contact_info {
string name;
string phone;
} Contact_info;
bool compareTo( const Contact_info &A, const Contact_info &B );
int main(void)
{
string name;
string phone;
UINT max_length = 0; // 가장 긴 이름
vector<Contact_info> chonbuk; // 전화번호가 063인 vector list
vector<Contact_info> elselocal; // 전화번호가 063이 아닌 vector list
typedef vector<Contact_info>::iterator contact_iter;
while( cin >> name )
{
if( max_length < name.size() ) // 가장 긴 이름 저장
max_length = name.size();
cin >> phone;
Contact_info contact;
contact.name = name;
contact.phone = phone;
string local = phone.substr(0, 3); // 앞의 지역번호 3자리만 따오기
if( local == "063" ) chonbuk.push_back(contact); // 063이면 chonbuk vectlist 에 push
else elselocal.push_back(contact); // 아니면 elselocal vector list에 push
}
// max_length - iter->name.size() 는 가장 긴 이름에서 현재 이름을 뺀
// 길이만큼의 공백에 기본공백 1개를 더함
if( chonbuk.size() > 0 )
{
sort( chonbuk.begin(), chonbuk.end(), compareTo ); // 정렬
cout << "area code 063" << endl;
for(contact_iter iter = chonbuk.begin() ; iter != chonbuk.end(); iter++ ) // vector 리스트 순회하면서 출력
{
string name = iter->name + string(max_length - iter->name.size() + 1, ' ');
cout << name << iter->phone << endl;
}
cout << endl;
}
if( elselocal.size() > 0 )
{
sort( elselocal.begin(), elselocal.end(), compareTo );
cout << "not area code 063" << endl;
for(contact_iter iter = elselocal.begin() ; iter != elselocal.end(); iter++ )
{
string name = iter->name + string(max_length - iter->name.size() + 1, ' ');
cout << name << iter->phone << endl;
}
}
return 0;
}
bool compareTo( const Contact_info &A, const Contact_info &B )
{
return A.name < B.name;
}
단어들을 입력받아 단어가 숫자를 포함하는지(Include digit), 특수문자를 포함하는지(Include special character), 알파벳으로만 되어 있는지(Only alphabet)에 따라 3 그룹으로 분류해서 단어를 사전순으로 출력하는 프로그램을 작성하시오.
cctype헤더파일에는 다음 함수들이 포함되어 있다.
isspace(c) : c가 공백문자이면 true 반환
isalpha(c) : c가 알파벳이면 true 반환
isdigit(c) : c가 숫자이면 true 반환
isalnum(c) : c가 알파벳이나 숫자이면 true 반환
Input
입력종료문자(EOF)가 입력되면 종료된다.
Output
출력형식은 다음과 같다.
Include digit
단어1
단어2
...
Include special character
단어1
단어2
...
Only alphabet
단어1
단어2
...
출력 조건은 다음과 같다.
1) 그룹 출력 순서는 Include digit, Include special character, Only alphabet순이다.
2) 그룹명은 해당 단어가 하나도 없으면 출력하지 않는다.
Sample Input1
tiger!
lion
monkey
4.bear
cat
Sample Output1
Include digit
4.bear
Include special character
4.bear
tiger!
Only alphabet
cat
lion
monkey
Sample Input2
java
ruby
C++
language
Sample Output2
Include special character
C++
Only alphabet
java
language
ruby
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <cctype>
using namespace std;
int main(void)
{
vector<string> digit;
vector<string> special;
vector<string> alphabet;
string word;
while(cin >> word)
{
bool flag = true;
for(string::iterator i = word.begin(); i != word.end(); i++)
{
if(isdigit(*i))
{
digit.push_back(word);
flag = false;
break;
}
}
for(string::iterator i = word.begin(); i != word.end(); i++)
{
if(!isalnum(*i))
{
special.push_back(word);
flag = false;
break;
}
}
if( flag == true )
alphabet.push_back(word);
}
if(digit.size() > 0)
{
sort(digit.begin(), digit.end());
cout << "Include digit" << endl;
for(vector<string>::iterator i = digit.begin(); i != digit.end(); i++)
cout << (*i) << endl;
cout << endl;
}
if(special.size() > 0)
{
sort(special.begin(), special.end());
cout << "Include special character" << endl;
for(vector<string>::iterator i = special.begin(); i != special.end(); i++)
cout << (*i) << endl;
cout << endl;
}
if(alphabet.size() > 0)
{
sort(alphabet.begin(), alphabet.end());
cout << "Only alphabet" << endl;
for(vector<string>::iterator i = alphabet.begin(); i != alphabet.end(); i++)
cout << (*i) << endl;
}
return 0;
}
어떻게 쉽게 하려고 해도 똥망진창이 되어가는 코드..
주석도 붙이려다가.. 결국은 안붙이게 되고..
#pragma once
#include <string>
using namespace std;
class Human
{
private:
string name;
string gender;
int age;
public:
Human( string aName, int aAge, string gender ); // Constructor
~Human( void ); // Destroyer
string getName( ); // getting a Name
int getAge( ); // getting a Age
string getGender( ); // getting a Gender
bool setName( string aName ); // change to Name
void growOld( ); // get on in years
void printName( ); // print to Name
void printAge( ); // print to Age
};
목적 : 수업시간에 분수를 클래스화 하는 실습을 진행하고 있고, 멘토링 모임을 진행하고 있어서 분수 클래스를 만들어 보기로 한다.
목표
1. 산술연산 및 대입연산, 관계연산이 모두 가능하도록 만들기로 한다.
2011년 10월 20일 목요일
헤더파일에 생성자와 파괴자, 연산자 오버로딩을 정의
Rational.h
#pragma once
#include <iostream>
#include <string>
class Rational
{
public:
// Constructor
Rational( int numerator, int denominator );
Rational( Rational& r );
Rational( Rational* r );
// Destroyer
~Rational( void );
// Overloading to output Object
friend std::ostream& operator <<( std::ostream& out, const Rational& T );
friend std::ostream& operator <<( std::ostream& out, const Rational* T );
// Overloading to arithmetic operators
Rational operator+ (const Rational& T) const;
Rational operator- (const Rational& T) const;
Rational operator* (const Rational& T) const;
Rational operator/ (const Rational& T) const;
// Overloading to assignment operator
Rational operator= (const Rational& T) const;
// Overloading to relational operators
Rational operator> (const Rational& T) const;
Rational operator>=(const Rational& T) const;
Rational operator< (const Rational& T) const;
Rational operator<=(const Rational& T) const;
Rational operator==(const Rational& T) const;
Rational operator!=(const Rational& T) const;
private:
int numerator;
int denominator;
// Common Denominator
const int gcdForDenominator(int a, int b) const;
// reduction of fractions to a common denominator
Rational reduceFration(int num, int den) const;
};
Rational.cpp
#include <iostream>
#include <stdexcept>
#include "Rational.h"
/*
* 2011년 10월 19일 분모와 분자를 인수로 하는 생성자 정의
* 2011년 10월 20일 Rational 객체를 인수로 하는 생성자 정의
*/
Rational::Rational( int numerator, int dendenominator )
{
this->numerator = numerator;
this->denominator = dendenominator;
}
Rational::Rational( Rational& r )
{
this->numerator = r.numerator;
this->denominator = r.denominator;
}
Rational::Rational( Rational* r )
{
this->numerator = r->numerator;
this->numerator = r->numerator;
}
/*
* 동적할당을 하는 멤버가 없기 때문에 멤버를 0으로 초기화
* 2011년 10월 19일 파괴자 or 소멸자 정의
*/
Rational::~Rational( void )
{
this->numerator = 0;
this->denominator = 0;
}
/*
* 2011년 10월 20일 << 연산자 오버로딩 출력을 위한 연산자
*/
std::ostream& operator<<( std::ostream& out, const Rational& T )
{
out << T.numerator << "/" << T.denominator;
return out;
}
std::ostream& operator<<( std::ostream& out, const Rational* T )
{
out << T->numerator << "/" << T->denominator;
return out;
}
/*
* 2011년 10월 19일 산술 연산자 오버로딩 구현
* 2011년 10월 20일 reduceFration 메서드 추가하여 중복코드 삭제
*/
Rational Rational::operator+( const Rational& T ) const
{
int num = (this->numerator * T.denominator) + (this->denominator * T.numerator);
int den = (this->denominator * T.denominator);
return this->reduceFration(num, den);
}
Rational Rational::operator-(const Rational& T) const
{
int num = (this->numerator * T.denominator) - (this->denominator * T.numerator);
int den = (this->denominator * T.denominator);
return this->reduceFration(num, den);
}
Rational Rational::operator*(const Rational& T) const
{
int num = (this->numerator * T.numerator);
int den = (this->denominator * T.denominator);
return this->reduceFration(num, den);
}
Rational Rational::operator/(const Rational& T) const
{
int num = (this->numerator * T.denominator);
int den = (this->denominator * T.numerator);
return this->reduceFration(num, den);
}
/*
* 2011년 10월 20일 대입 연산자 오버로딩 구현
*/
Rational Rational::operator =(const Rational& T) const
{
Rational R(T.numerator, T.denominator);
return R;
}
/*
* 2011년 10월 20일 통분을 위한 멤버 메서드
*/
Rational Rational::reduceFration(int num, int den) const
{
int commonDenominator = this->gcdForDenominator(num, den);
Rational R(num / commonDenominator, den / commonDenominator);
return R;
}\/*
* 2011년 10월 19일 통분을 위한 약수를 구하는 메서드
*/
const int Rational::gcdForDenominator(int a, int b) const
{
a = std::abs(a);
b = std::abs(b);
if( a < b ) std::swap(a, b);
while( b > 0 )
{
int temp = a % b;
a = b;
b = temp;
}
return a;
}