我正在尝试编写一个显示1到100之间整数的程序,这些整数可被6或7 整除,但不能同时。
这是我的代码:
import acm.program.*;
public class Problem4 extends ConsoleProgram
{
public void run()
{
for (int i = 1; i <= 100; i++)
{
boolean num = ((i % 6 == 0) || (i % 7 == 0));
if (num == true)
println(i + " is divisible");
}
}
}
以上代码显示以下答案: 6,7,12,14,18,21,24,28,30,35,36,的 42 下,48,49,54,56,60,63,66,70,72,77 ,78,的 84 下,90,91,96,98
现在粗体数字42和84都是6和7的divisbile。现在如果我在上面的代码中将||
更改为&&
,结果只显示42和84.
我应该做些什么改变才能从最终结果中删除这两个数字?
答案 0 :(得分:19)
XOR是要走的路。
import acm.program.*;
public class Problem4 extends ConsoleProgram {
public void run() {
for (int i = 1; i <= 100; i++) {
if ( (i % 6 == 0) ^ (i % 7 == 0) ) {
println(i + " is divisible");
}
}
}
}
答案 1 :(得分:8)
你必须让你的情况看起来像:
boolean num = (i % 6 == 0 || i % 7 == 0) && !(i % 6 == 0 && i % 7 == 0);
基本上将“但不是两个”转换为Java代码:)
答案 2 :(得分:5)
您需要额外检查“但不是两者”。我认为应该是:
boolean num =((i%6 == 0)||(i%7 == 0))&amp;&amp; (i%42!= 0);
答案 3 :(得分:5)
您也可以尝试
boolean num = ((i % 6 == 0) != (i % 7 == 0));
答案 4 :(得分:2)
想想被6和7整除是什么意思......宇宙和万物生命的答案。
答案 5 :(得分:1)
import acm.program.*;
public class Problem4 extends ConsoleProgram
{
public void run()
{
for (int i = 1; i <= 100; i++)
{
boolean num = ((i % 6 == 0) || (i % 7 == 0));
boolean both = ((i % 6 == 0) && (i % 7 == 0));
if ((num == true) && (both == false))
println(i + " is divisible");
}
}
}
答案 6 :(得分:0)
这是一个应该在C ++中运行良好的片段,但更改为boolean ...
int value;
if ((value % 6 == 0 && value % 7 != 0) || (value % 6 != 0 && value % 7 == 0))
cout << "Is " << value << " divisible by 6 or 7, but not both? true" << endl;
else
cout << "Is " << value << " divisible by 6 or 7, but not both? false" << endl;
答案 7 :(得分:0)
简化版
for(int i=1; i<=100; i++) {
// Either Divisible by 6 or 7 but not both
if((i%6==0 && i%7!=0) ||( i%7==0 && i%6!=0)) {
println(i);