我的问题与以下代码有关:
public static void main(String[] args) {
// Find Prime Numbers from 0 to 100
int i;
for (i=2; i <= 100; i++) {
int j = 2;
boolean iPrime = true;
//The following line gives incorrect results, but should execute faster
// while ((iPrime = true) && (j < (i / 2 + 1))) {
//The following line gives correct results but performs un-necessary operations
//by continuing to calculate after the number is found to be "not prime"
while (j < (i / 2 + 1)) {
j++;
if ((i % j) == 0) {
iPrime = false;
//System.out.println(j + " is a factor of " + i);
}
}
if (iPrime) {
System.out.println(i + " is a prime number!");
}
}
}
现在,正如我在代码中评论的那样,我试图实现的是通过仅在 iPrime = true 时执行“while”循环来更快地执行我的程序。 50% 的数字可以被 2 整除,因此一旦确定,计算就可以停止。
我正在做这个项目作为一本书中初学者“示例”的一部分,实际上我正在尝试尽快计算高达 1000000 只是为了我自己的“额外学分”......
我读到“短路‘与’运算符”&& 仅在前半部分为真时才评估语句的后半部分,如果为假,则两者不会相互评估(节省 CPU)
而且它还会退出循环,这会节省更多的 CPU...
但由于某些原因,它无法正常工作!我在整个过程中放置了更多 System.out.println() 语句,列出了“iPrime”是什么 - 输出很奇怪......它打开和关闭 iPrime 并计算每个我无法理解的数字。
最佳答案
if((iPrime = true) && ...)
应该是 if((iPrime) && ...)
。
通过执行 isPrime = true
然后您将分配 true 给 isPrime
而不是比较它的值真
。
您可能还想查看 this为了更好地理解您的代码中发生了什么:
At run time, the result of the assignment expression is the value of the variable after the assignment has occurred. The result of an assignment expression is not itself a variable.
因此,当您使用 =
运算符而不是 ==
时(当您将某些内容与 true
进行比较时,它会被删除 - 而不是编写if(someBoolean == true)
你只要写 if(someBoolean)
),你就满足了条件,总是!
关于java - 在 switch 语句中使用逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16121082/