코딩 및 기타

c++ 복습 3-6~3-9

정지홍 2023. 2. 21. 09:58

3-6
#include <iostream>
#include <cstdlib>
using namespace std;
class EvenRandom {
public:
int next();
int nextInRange(int x, int y);
int checkEven(int a);
};
int EvenRandom::checkEven(int a) {
if (a % 2 == 0) {
return a;
}
else {
int x = rand();
return checkEven(x);
}
}
int EvenRandom::next() {
int a = rand();
return checkEven(a);
}
int EvenRandom::nextInRange(int x, int y) {
int a = rand() % (y) + x;
if (a % 2 == 0) {
return a;
}
else {
return nextInRange(x, y);
}
}
int main() {
srand(time(NULL));
EvenRandom r;
cout << "--0에서" << RAND_MAX << "까지의 랜덤 정수 10개--" << endl;
for (int i = 0; i < 10; i++) {
int n = r.next();
cout << n << ' ';
}
cout << endl << endl << "--2에서 " << "10까지의 랜덤 정수 10개--" << endl;
for (int i = 0; i < 10; i++) {
int n = r.nextInRange(2, 10);
cout << n << ' ';
}
}


3-7
#include <iostream>
#include <cstdlib>
using namespace std;

class Random {
public:
int next();
int oddRange(int x,int y);
int evenRange(int x, int y);
};

int Random::next() {
return rand();
}

int Random::evenRange(int x, int y) {
int a;
do {
a = x + rand() % (y);
} while (a % 2 == 1);

return a;
}

int Random::oddRange(int x, int y) {
int a;
do {
a = x + rand() % (y);
} while (a % 2 == 0);

return a;
}

int main() {
srand(time(NULL));
Random r;
cout << "--0에서" << RAND_MAX << "까지의 랜덤 짝수 10개--" << endl;
for (int i = 0; i < 10; i++) {
int n = r.evenRange(0,RAND_MAX);
cout << n << ' ';
}
cout << endl << endl << "--2에서 " << "9까지의 랜덤 홀수 10개--" << endl;
for (int i = 0; i < 10; i++) {
int n = r.oddRange(2, 9);
cout << n << ' ';
}

}


3-8


#include <iostream>
#include <string>
using namespace std;
class Integer {
int n;
public:
Integer(int n) {
this->n = n;
}
Integer(string n) {
this->n = stoi(n);
}
void set(int n) {
this->n = n;
}
int get() {
return n;
}
int isEven() {
return true;
}
};
int main() {
Integer n(30);
cout << n.get() << ' '; //30출력
n.set(50);
cout << n.get() << ' ';//50출력

Integer m("300");
cout << m.get() << ' ';
cout << m.isEven();
}


3-9

#include <iostream>
class Oval {
int width, height;
public:
Oval();
Oval(int x, int y);
int getWidth() { return width; };
int getHeight() { return height; };
void set(int w, int h);
void show();
~Oval();
};

 Oval::Oval() {
width = 1;
height = 1;
}
 Oval::Oval(int x, int y) {
 width = x; height = y;
 }
 void Oval::set(int w, int y) {
 this->width = w;
 this->height = y;
 }
 void Oval::show() {
 std::cout << this->width << "," << this->height  << "\n";
 }
 Oval::~Oval() {
 std::cout << "\nOval소멸 : width = " << this->width << ", height = " << this->height << "\n";
 }
 int main() {
 Oval a, b(3, 4);
 a.set(10, 20);
 a.show();
 std::cout << b.getWidth() << "," << b.getHeight() ;
 }