반응형

6.7> 다음과 같은 static 멤버를 가진 Random 클래스를 완성하라(Open Challenge 힌트참고). 그리고 Random 클래스를 이용하여 다음과 같이 랜덤한 값을 출력하는 main() 함수도 작성하라. Main()에서 Random 클래스의 seed() 함수를 활용하라.

<코드>

#include <iostream>

#include <ctime> //time 함수 사용 위함

#include <stdlib.h> //rand, srand, RAND_MAX 사용 위함

 

using namespace std;

 

class Random{

public:

        static void seed(){srand((unsigned)time(0));} //현재 시간으로 랜덤 시드 초기화

        static int nextInt(int min=0, int max=32767); //디폴트 매개변수 min=0, max=32767(RAND_MAX)

        static char nextAlphabet();

        static double nextDouble();

};

int Random::nextInt(int min, int max){ //함수 구현시 디폴트 매개 변수 다시 입력하지 않는다.

        return rand()%(max-min+1)+min; //min 이상 max 이하 랜덤 출력

}

char Random::nextAlphabet(){ //'A'=65 'Z'=90 'a'=97'z'=122

        if(rand()%2) //1이면 대문자

        return rand()%(26)+65; //대문자 리턴

        else //아니면 소문자

        return rand()%(26)+97; //소문자 리턴

}

double Random::nextDouble(){ //실수로 강제형변환한 rand 최대 나올수 있는 수를 실수로 형변환 것으로 나눠준다

        return (double)rand()/(double)RAND_MAX; //RAND_MAX rand함수가 반환하는 가장 (32767)

}

 

int main(void){

        int i;

        Random::seed(); //시드 초기화

        cout<<"1에서 100까지 랜덤한 정수 10개를 출력합니다."<<endl;

        for(i=0;i<10;i++){cout<<Random::nextInt(1,100)<<" ";}

        cout<<endl;

        cout<<"알파벳을 랜덤하게 10개를 출력합니다."<<endl;

        for(i=0;i<10;i++){cout<<Random::nextAlphabet()<<" ";}

        cout<<endl;

        cout<<"랜덤한 실수를 10 출력합니다."<<endl;

        for(i=0;i<10;i++){cout<<Random::nextDouble()<<" ";}

        cout<<endl;

 

        return 0;

}

<결과창>

 

                                  


반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

Matrix class  (0) 2017.12.25
Trace 클래스  (0) 2017.12.25
배열 빼기  (0) 2017.12.25
동일한 크기의 배열  (0) 2017.12.25
생성자 오버로딩의 디폴트 매개변수로의 변환  (0) 2017.12.25

+ Recent posts