我想做一個簡單的程序,將顯示1到100之間的20個隨機數,然後打印出哪些數字可以被3整除,相當於1%3和2%3。它似乎工作得很好,但我注意到它只適用於列表中最後一個數字。我錯過了在搜索數學中包含所有數字的情況?提前感謝您的幫助,我可以得到!需要幫助使用隨機數和模
import java.util.Random;
public class Lab5 {
public static void main(String[] args) {
Random rnd = new Random();
int repeat = 19;
int n = 0;
for(int i=0;i<=repeat;i++){
n = rnd.nextInt(100)+1;
System.out.print(n+", ");
}
System.out.println();
System.out.println("-------------------------------------");
if(n % 3 == 0){
System.out.println("Numbers divisible by three: "+n+(", "));
}else{
System.out.println("Numbers divisible by three: NONE");
}
System.out.println("-------------------------------------");
if(n == 1 % 3){
System.out.println("Numbers equivalent to one modulo three: "+n+(", "));
}else{
System.out.println("Numbers equivalent to one modulo three: NONE");
}
System.out.println("-------------------------------------");
if(n == 2 % 3){
System.out.println("Numbers equivalent to two modulo three: "+n+(", "));
}else{
System.out.println("Numbers equivalent to two modulo three: NONE");
}
}
}
您正在執行'for'循環的20次迭代,每次計算n次。然後,在for循環終止之後,你執行'if'塊。你需要在for循環中執行數學運算。 – deanosaur
或者,將數字存儲到數組(或集合)中,然後對數組中的值進行數學運算。 –