게시판 |
상위분류 : 잡필방 | 중위분류 : 서류가방 | 하위분류 : 전산과 컴퓨터 |
작성자 : 문시형 | 작성일 : 2024-02-01 | 조회수 : 1,490 |
이번 포스팅은 C#에서 특정 범위의 랜덤 값을 생성할 수 있는 몇 가지 방법을 소개합니다.
특정 범위의 랜덤 값을 생성하기 위해 Random 클래스의 next() 메서드를 사용합니다.
public virtual int Next(int minValue, int maxValue)
Next() 메서드는 최소값(minValue), 최대값(maxValue) 사이의 값을 반환합니다.
최소값이 0이며, 최대값이 10인 경우 0 이상 10 미만인 정수를 반환합니다.
다음 예제는 0 이상 10 미만인 랜덤 값을 콘솔에 5번 출력합니다.
class Program
{
static void Main(string[] args)
{
Random rand = new Random();
for(int loop = 0; loop < 5; loop++)
{
Console.WriteLine("0 ~ 10 사이의 랜덤 값: " + rand.Next(0, 10));
}
}
}
[실행 결과]
0 ~ 10 사이의 랜덤 값: 8
0 ~ 10 사이의 랜덤 값: 2
0 ~ 10 사이의 랜덤 값: 6
0 ~ 10 사이의 랜덤 값: 9
0 ~ 10 사이의 랜덤 값: 6
Next() 메서드에 전달되는 최소값은 최대값보다 클 수 없습니다. 만약, 최소값이 최대값보다 큰 경우 ArgumentOutOfRangeException이 발생합니다.
class Program
출처: https://developer-talk.tistory.com/749 [DevStory:티스토리]
2. C# random(랜덤) 예제 및 사용법
namespace RandomExample { class Program { main을 포함해야하는 왼쪽 것은 코드가 오른쪽으로 길어지기 때문에 생략하였습니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
//C# Random Class Example. BlockDMask. using System; static void Main(string[] args) { Random rand = new Random();
//1. Next() Console.WriteLine("1. Next()"); for (int i=0; i < 10; ++i) { int a = rand.Next(); Console.WriteLine("Next() : " + a); }
//2. Next(min, max) Console.WriteLine("\n2. Next(min, max)"); for (int i = 0; i < 10; ++i) { int a = rand.Next(1, 5); Console.WriteLine("Next(1, 5) : " + a); }
//3. Next(max) Console.WriteLine("\n3. Next(max)"); for (int i = 0; i < 10; ++i) { int a = rand.Next(5); Console.WriteLine("Next(5) : " + a); }
//4. 응용1 (배열안의 랜덤) Console.WriteLine("\n4. 문자열 배열의 랜덤 index를 가지고 오기"); string[] str = { "BlockDMask", "Random", "C# example", "Blog", "Programmer" }; for (int i = 0; i < 10; ++i) { //randomIndex는 str.Length 보다 작은 음이 아닌 정수를 반환하기 때문에, //랜덤값을 배열의 index로 바로 사용해도 상관없는 상황이 됩니다. int randomIndex = rand.Next(str.Length); //Next(Max). Console.WriteLine("randomIndex = {0}, str[randomIndex] = {1}", randomIndex, str[randomIndex]); }
//5. NextBytes(byte[] buffer) Console.WriteLine("\n5. NextBytes(byte[] buffer)"); byte[] arrByte = new byte[5]; rand.NextBytes(arrByte); //한번 호출에 배열 모든 요소 랜덤값 세팅
for (int i = 0; i < arrByte.Length; ++i) { Console.WriteLine("arrByte[{0}] : {1}", i, arrByte[i]); }
//6. NextDouble() Console.WriteLine("\n6. NextDouble()");
for (int i = 0; i < 10; ++i) { double d = rand.NextDouble(); Console.WriteLine("NextDouble() : " + d); } } |
출처: https://blockdmask.tistory.com/347 [개발자 지망생:티스토리]
| | 목록으로