我想做一个小程序,通过添加两个随机数来得到所需的结果。例如,我们想要的数字是30,那么随机的NO1和NO2应该是15-15,13-17,10-20或其他任何东西。我制作了这个程序,它显示随机数的和,但不是期望的和。
import java.util.*;
import java.util.Random;
public class Problem {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random rand = new Random();
Random random = new Random();
int r = rand.nextInt(100) + 1;
int r1 = random.nextInt(100) + 1;
int sum = r + r1;
System.out.println(r + " + " + r1 + " sum is: " + sum);
}
}解决了这个问题。
import java.util.*;
import java.util.Random;
public class Problem {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
Random rand= new Random();
Random random= new Random();
int r= rand.nextInt(100)+1;
int n=0;
int sum= sc.nextInt();
n= sum-r;
sum= r+n;
System.out.println(r +" + "+n+ " sum is: " + sum);
}
}发布于 2016-09-10 05:58:39
你的问题并不在你的代码中;但是你的逻辑/数学是有缺陷的:你看,当你得到三个数字时,就像
M+n=o
M是一个随机数,o是固定的,那么n =o.
因此:您只需要一个随机数,而不是两个!
发布于 2016-09-10 05:59:29
只需选择与和的上限在范围内的第一个数字,然后保留第二个数字作为和和与第一个数的差:
Random rn = new Random();
int max = 30;
int first = rn.nextInt(max) + 1;
int second = max - first;现在,first和second被认为是最大的总和。我假设,对于给定的和max,最小的数是1。
发布于 2016-09-10 06:00:00
我想你是在找这个
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Random rand = new Random();
int r1 = rand.nextInt(n) + 1; // only one random number is needed
int r2 = n-r1; // other will be subtract of n and r1
System.out.println(r1 + " + " + r2 + " sum is: " + n);https://stackoverflow.com/questions/39423062
复制相似问题