본문 바로가기
.NET

C# Random 함수 사용

by leo21c 2025. 5. 13.

C#에서는 rand()라는 함수가 따로 존재하지 않지만, 난수를 생성할 때는 System.Random 클래스를 사용합니다.

 

1. 기본적인 난수 생성

Random rand = new Random();
int randomNumber = rand.Next(); // 0 이상 int.MaxValue 미만의 랜덤 숫자 생성
Console.WriteLine(randomNumber);

 

💡 rand.Next()는 int 범위 내에서 난수를 생성합니다.

 

2. 특정 범위의 난수 생성
만약 1부터 100 사이의 난수를 생성하려면 다음과 같이 사용할 수 있습니다:

int randomNumber = rand.Next(1, 101); // 1 이상 100 이하의 난수 생성
Console.WriteLine(randomNumber);

 

💡 rand.Next(min, max)를 사용하면 min 이상 max 미만의 숫자를 생성합니다.

 

3. 실수형(Random floating-point) 난수 생성
만약 0 이상 1 미만의 난수를 얻고 싶다면 NextDouble()을 사용하세요:

double randomDouble = rand.NextDouble(); // 0.0 이상 1.0 미만의 난수 생성
Console.WriteLine(randomDouble);

 

4. 배열에서 랜덤 값 선택

string[] colors = { "Red", "Blue", "Green", "Yellow", "Purple" };
string randomColor = colors[rand.Next(colors.Length)];
Console.WriteLine($"랜덤 색상: {randomColor}");

 

💡 rand.Next(array.Length)를 사용하여 배열에서 랜덤한 값을 선택할 수 있습니다.

 

🧐 중요한 사항
Random 인스턴스를 너무 자주 생성하면 난수가 예상보다 덜 무작위로 보일 수 있습니다. 따라서 Random 객체를 반복문 안에서 새로 생성하지 않고 한 번만 생성 후 사용하는 것이 좋습니다.

멀티스레드 환경에서는 Random보다 System.Security.Cryptography.RandomNumberGenerator를 고려하세요.

LIST