我需要编写一段代码来查找余数为的最小整数:
• 除以 3 为 1
• 除以 5 时为 2
• 除以 7 时为 3
我尝试了以下代码,但我的输出是1。我尝试更改初始值,但它仍然只输出初始值。
public static void main (String[] args)
{
int i=2;
while((i%3)!=1 && (i%5)!=2 && (i%7)!=3) {
i++;
}
System.out.print(i);
}
最佳答案
您在 while
循环中的条件不正确,应该是:
while((i%3)!=1 || (i%5)!=2 || (i%7)!=3)
为什么?
您需要找到第一个适用的数字:
a%3 == 1 and a%5 == 2 and a%7 == 3
为此,您需要跳过以下位置的所有数字:
not(a%3 == 1 and a%5 == 2 and a%7 == 3)
如果您申请De Morgan's laws你得到:
a%3 != 1 or a%5 != 2 or a%7 != 3
关于java - while 循环不遵守退出条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58330621/