【问题标题】:The output of this code should be 0 why am I getting 1 as a result? Please tell the error这段代码的输出应该是 0 为什么我得到 1 结果?请告诉错误
【发布时间】:2015-08-27 11:12:59
【问题描述】:

其实我正在写一个计算除以3的总数的方法。我的代码是:

class Simple{  

    public static int countDivisible(int lowerBound, int upperBound)
    {
        int counter = 0;
        for(int i=lowerBound; i< upperBound; i++)
        {
            if((i%3)==0)
            counter++;

        }

        return counter;

    }


    public static void main(String args[]){  

        int num;
        num = countDivisible(17,19);
        System.out.println("total= "+num);

    }        

} 

例如,如果调用 countDivisible(3, 9),则返回值 2。这是因为在整数范围 [3, 4, 5, 6, 7, 8, 9] 中只有两个数字 3 和 6 可以被 3 整除,但不能被 9 整除

【问题讨论】:

  • 那么,错误是什么?在您的代码中,18 是可整除的。因此输出为1
  • 错误是什么?输出 1 是正确的
  • “但不是 9”。您的代码中没有任何内容。
  • 在17到19的范围内,18是3的整除数,计数为1。

标签: java class methods


【解决方案1】:

您将 18 置于条件中

18%3 == 0

【讨论】:

    猜你喜欢
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    相关资源
    最近更新 更多