IT박스

Java가 주어진 두 값 사이에서 난수를 생성 함

itboxs 2020. 6. 30. 20:58
반응형

Java가 주어진 두 값 사이에서 난수를 생성 함


이 질문에는 이미 답변이 있습니다.

주어진 두 값 사이에 임의의 숫자를 생성하는 방법을 알고 싶습니다.

다음을 사용하여 난수를 생성 할 수 있습니다.

Random r = new Random();

for(int i = 0; i < a.length; i++){
    for(int j = 0; j < a[i].length; j++){
        a[i][j] = r.nextInt();
    }

}

그러나 0에서 100 사이의 난수를 어떻게 생성 할 수 있습니까?


당신은 예를 들어 사용할 수 있습니다 r.nextInt(101)

보다 일반적인 "두 숫자 사이"를 사용하려면 다음을 사용하십시오.

Random r = new Random();
int low = 10;
int high = 100;
int result = r.nextInt(high-low) + low;

10 (포함)에서 100 (제외) 사이의 난수를 제공합니다.


상한이 상한이고 하한이 하한이라고 가정하면 다음을 사용하여 두 경계 사이에 난수 r을 만들 수 있습니다.

int r = (int) (Math.random() * (upper - lower)) + lower;

int Random = (int)(Math.random()*100);

둘 이상의 값을 생성 해야하는 경우 for 루프를 사용하십시오.

 for (int i = 1; i <= 10 ; i++)
       {
        int Random = (int)(Math.random()*100);
        System.out.println(Random);
       }

10에서 100과 같이 더 적절한 범위를 지정하려는 경우 (둘 다 범위에 있음)

코드는 다음과 같습니다.

   int Random =10 +  (int)(Math.random()*(91));
   /* int Random = (min.value ) + (int)(Math.random()* ( Max - Min + 1));
  *Where min is the smallest value You want to be the smallest number possible to       
  generate and Max is the biggest possible number to generate*/

이렇게

Random random = new Random();
int randomNumber = random.nextInt(upperBound - lowerBound) + lowerBound;

Random.nextInt (int) 사용하십시오 .

귀하의 경우 다음과 같이 보일 것입니다 :

a[i][j] = r.nextInt(101);

Java에는 Python과 같은 방식으로 두 값 사이에 임의 생성기가 없습니다. 실제로 랜덤을 생성하는 데는 하나의 값만 필요합니다. 따라서해야 할 일은 생성 된 숫자에 ONE CERTAIN NUMBER를 추가하여 숫자가 범위 내에 있도록하는 것입니다. 예를 들어 :

package RandGen;

import java.util.Random;

public class RandGen {


    public static Random numGen =new Random();

public static int RandNum(){
    int rand = Math.abs((100)+numGen.nextInt(100));

    return rand;
}

public static void main(String[]Args){
   System.out.println(RandNum());
}

}

This program's function lies entirely in line 6 (The one beginning with "int rand...". Note that Math.abs() simply converts the number to absolute value, and it's declared as an int, that's not really important. The first (100) is the number I am ADDING to the random one. This means that the new output number will be the random number + 100. numGen.nextInt() is the value of the random number itself, and because I put (100) in its parentheses, it is any number between 1 and 100. So when I add 100, it becomes a number between 101 and 200. You aren't actually GENERATING a number between 100 and 200, you are adding to the one between 1 and 100.


One can also try below:

public class RandomInt { 
    public static void main(String[] args) { 

        int n1 = Integer.parseInt(args[0]);
        int n2 = Integer.parseInt(args[1]);
        double Random;

        if (n1 != n2)
        {
            if (n1 > n2)
            {
                Random = n2 + (Math.random() * (n1 - n2));
                System.out.println("Your random number is: " + Random);
            }
            else
            {
                Random = n1 + (Math.random() * (n2 - n1));   
                System.out.println("Your random number is: " +Random);
            }
        } else {
            System.out.println("Please provide valid Range " +n1+ " " +n2+ " are equal numbers." );
        }                     
    }
}

참고URL : https://stackoverflow.com/questions/5271598/java-generate-random-number-between-two-given-values

반응형