嗨,我是编程新手,我正在尝试制作一个可以生成2个随机数的除法程序,条件是第一个数必须大于第二个数,并且它们不给出余数。如果生成的数字不满足条件,它将继续生成,直到满足条件为止。有人能帮我纠正错误吗?
randomnum1 = 1 + (int)(Math.random()*9);
randomnum2 = 1 + (int)(Math.random()*9);
while (randomnum1 < randomnum2 && randomnum1/randomnum2 % 2 != 0) {
randomnum1 = 1 + (int)(Math.random()*9);
randomnum2 = 1 + (int)(Math.random()*9);
int number1 = randomnum1;
int number2 = randomnum2;
int a = number1/number2;
//rest of program is below this
您的while
条件检查除法结果是否为偶数randomnum1/randomnum2 % 2 != 0
您应该替换:
while (randomnum1 < randomnum2 && randomnum1/randomnum2 % 2 != 0) {
带
while (randomnum1 < randomnum2 || randomnum1 % randomnum2 != 0) {
// while (!(randomnum1 >= randomnum2 && randomnum1 % randomnum2 == 0)) {
randomnum1 = 1 + (int)(Math.random()*9);
randomnum2 = 1 + (int)(Math.random()*9);
}
// randomnum1 and randomnum2 now match your expectations
int a = number1/number2;
由于rand1 modulo rand2 == 0
意味着
他们不给出余数
另一种方法是使用无限循环,并在满足条件时中断循环。
public class Main {
public static void main(String[] args) {
int randomNum1, randomNum2;
while (true) {// An infinite loop
randomNum1 = 1 + (int) (Math.random() * 9);
randomNum2 = 1 + (int) (Math.random() * 9);
if (randomNum1 > randomNum2 && randomNum1 % randomNum2 == 0) {
System.out.println(randomNum1 + " / " + randomNum2 + " = " + (randomNum1 / randomNum2));
break;// Break the loop
}
}
}
}
样本运行:
8 / 2 = 4
public static void main(String[] args) {
int randomnum1=1 + (int)(Math.random()*99);
int randomnum2=1 + (int)(Math.random()*99);
while(randomnum1 % randomnum2 != 0 || randomnum1==randomnum2) {
//prints first numbers generated
System.out.println(randomnum1+" "+randomnum2);
randomnum1=1 + (int)(Math.random()*99);
randomnum2=1 + (int)(Math.random()*99);
}
if (true) {
//prints numbers generated that made the statement true
System.out.print("true :"+randomnum1+" "+randomnum2);
}
}
}
一个更好的方法,不必使用任何循环,就是做一些数学技巧,如下所示:
public class SpecialRandom{
public void generate(){
int first = 2 + (int) (Math.random() * 99);
int second = 1 + (int) (Math.random() * 99);
// to guarantee the second is always smaller
if (second>=first){ second%=first; }
if (second==0) { second++; }
first += second - (first%second); //to correct remainder
System.out.println((first>second && first%second==0)
+ " : " +first+ " , " +second);
}
/*TESTING*/
public static void main(String []args){
SpecialRandom sr = new SpecialRandom();
for(int j=0; j<25; j++){ sr.generate(); }
}
}
结果
true : 28 , 4
true : 64 , 32
true : 22 , 11
true : 18 , 3
true : 28 , 14
true : 18 , 6
true : 92 , 23
true : 96 , 6
true : 130 , 65
true : 28 , 14
true : 87 , 29
true : 87 , 29
true : 74 , 37
true : 112 , 56
true : 66 , 6
true : 10 , 1
true : 88 , 44
true : 68 , 34
true : 156 , 78
true : 22 , 11
true : 95 , 1
true : 86 , 43
true : 14 , 1
true : 82 , 41
true : 98 , 14