🚫ERROR
[C2365, C4430, E0077 에러, Visual Studio] srand오류 "이 선언에는 스토리지 클래스 또는 형식 지정자가 없습니다.", "missing type specifier"
Cocoon_
2020. 5. 20. 22:54
반응형
랜덤난수 발생 코드는 처음 써봐서 오늘 제가 겪었던 오류에 대해 포스팅하고자 합니다.
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
srand((unsigned)time(0)); // 시작할때마다 다른 랜덤 수를 발생시키는 seed 설정
int n = rand();
int main()
{
cout << n << endl;
}
코드는 미완성이였는데 srand 부분에서 계속 빨간줄이 생겨서 무엇이 문제인지 알아보았습니다.
C4430 에러의 경우 "모든 선언에는 명시적으로 형식을 지정"해야하므로 srand 앞에 int를 붙였더니 빨간줄이 사라졌습니다. 그래서 실행시켜보니...
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int srand((unsigned)time(0)); // 시작할때마다 다른 랜덤 수를 발생시키는 seed 설정
int n = rand();
int main()
{
cout << n << endl;
}
여전히 에러가 발생하였습니다. 그리하여 C2365 에러를 검색해보니
" 'class member': 재정의: 이전 정의는 'class member'입니다. 클래스 멤버를 다시 정의하려고 했습니다."
즉, 이미 정의되어있는 클래스이므로 다시 정의를 해서는 안되며, 전역 범위에서는 함수, 변수등을 선언, 정의만 할 수 있기 때문에 srand 코드부분은 함수 내부에 있어야 한다는 것을 깨달았습니다.
<올바른 srand 사용법>
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
srand((unsigned)time(0)); // 시작할때마다 다른 랜덤 수를 발생시키는 seed 설정
int n = rand();
cout << n << endl;
}
<랜덤난수 10개 생성하기>
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
srand((unsigned)time(0)); // 시작할때마다 다른 랜덤 수를 발생시키는 seed 설정
for (int i = 0; i < 10; i++)
{
int n = rand();
cout << n << endl;
}
}
반응형