我试图写显示由6或7的整除1到100之间的整数的一个节目但不能同时

下面是我的代码:

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

现在的粗体数字42和84都通过divisbile 6和7立即如果更改||在上面的代码&&,结果表明

我应该做些什么变化,从最终结果中删除这些2个数字?

有帮助吗?

解决方案

你必须让你的病情是这样的:

boolean num = (i % 6 == 0 || i % 7 == 0) && !(i % 6 == 0 && i % 7 == 0);

这基本上是转换 “的但不能同时” 到Java代码:)

其他提示

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");
      }
    }
  }
}

您需要额外的检查“但不能两者都”。我觉得应该是:

布尔NUM =((I%6 == 0)||(ⅰ%7 == 0))&&(ⅰ%42!= 0);

您也可以尝试

boolean num = ((i % 6 == 0) != (i % 7 == 0));

想想这意味着什么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));
            boolean both = ((i % 6 == 0) && (i % 7 == 0));

            if ((num == true) &&  (both == false))
            println(i + " is divisible");
        }
    }
}

下面是应作为良好工作在C ++中,但改变为布尔片段...

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;

:一种小简化版本

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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top