简体   繁体   中英

How to add two random numbers within a range?

My requirement :--

The sum of the two random numbers will be 100..
      sum=random_no1 + random_no2  (the sum will be exact 100)

So,I have tried:--

Random r = new Random();
        int Low = 10;
        int High = 100;
        int R = r.nextInt(High-Low) + Low;

    Random r1 = new Random();
    int Low1 = 10;
    int High1 = 100;
    int R1 = r1.nextInt(High1-Low1) + Low1;

but how I define the sum??

I can not understand..Please help me..

Well, based on your requirements I'd suggest you just subtract your first random number from 100. Then you have two random numbers with that sum. Finally, Java naming convention is lower case letter first. Like,

Random r = new Random();
int low = 10;
int high = 100;
int r1 = r.nextInt(high - low) + low;
int r2 = 100 - r1; // <-- so that r1 + r2 is 100
max =100;
min = 10;

FirstOne = Math.floor(Math.random()*(max-min))+min;

secondOne = Math.floor(Math.random()*(max-FirstOne));

sum = FirstOne+secondOne;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM