我正在尝试制作如下程序
“从用户获取整数n;找到前n个复合数字;在行中显示这些数字,使每行包含5个数字。例如,如果用户输入10,则程序需要输出
4 6 8 9 10
12 14 15 16 18“
问题是当我输入一些要显示的整数时,它会显示一个小于预期的值,就像我输入'10'表示整数,它打印出9个整数。
import java.util.Scanner;
public class hello { public static void main(String [] args){
int n;
int status = 1;
int num = 1;
int count = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of composite numbers you wish to view:");
n = input.nextInt();
System.out.println("The first " + n + " composite numbers are:");
for (int i = 2; i <= n;) {
for (int j = 2; j <= Math.sqrt(num); j++) {
if (num % j == 0) {
status = 0;
break;
}
}
if (status == 0) {
System.out.print(num + " ");
i++;
count++;
}
status = 1;
num++;
if (count == 5) {
System.out.println();
count = 0;
}
}
}
}
答案 0 :(得分:0)
在以下循环中使用i
初始化2
是否有任何特定原因:
for (int i = 2; i <= n;) {
如果我们使用i
初始化1
,则每行似乎显示5个数字,例如:
for (int i = 1; i <= n;) {
for (int j = 2; j <= Math.sqrt(num); j++) {
if (num % j == 0) {
status = 0;
break;
}
}
if (status == 0) {
System.out.print(num + " ");
i++;
count++;
}
status = 1;
num++;
if (count == 5) {
System.out.println();
count = 0;
}
}