【发布时间】:2017-03-05 02:39:12
【问题描述】:
好吧,我的问题不是如何判断一个数字是否是素数,因为我想我已经弄清楚了,而是如何让它正确显示。
这是我的代码:
public static void main(String[] args) {
// Declare Variables
int randomNumbers = 0;
int sum = 0;
//Loop for number generation and print out numbers
System.out.print("The five random numbers are: ");
for (int i = 0; i <= 4; i++)
{
randomNumbers = (int)(Math.random()*20);
sum += randomNumbers;
if (i == 4) {
System.out.println("and " + randomNumbers + ".");
}
else {
System.out.print(randomNumbers + ", ");
}
}
//Display Sum
System.out.println("\nThe sum of these five numbers is " + sum + ".\n");
//Determine if the sum is prime and display results
for(int p = 2; p < sum; p++) {
if(sum % p == 0)
System.out.println("The sum is not a prime number.");
else
System.out.println("The sum is a prime number.");
break;
}
}
}
现在我的问题是,如果数字最终是 9,它会说它是质数,但它不是。我认为问题在于 break 在一个循环后停止它,所以它不会增加变量 p 所以它只是测试除以 2(我认为)。但是,如果我删除断点,它将在每次传递时打印出“总和是/不是素数”,直到它退出循环。不知道在这里做什么。
【问题讨论】: