首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么当if语句只有两次为真时,for循环会发生3次?

为什么当if语句只有两次为真时,for循环会发生3次?
EN

Stack Overflow用户
提问于 2018-09-07 22:57:04
回答 2查看 107关注 0票数 -1

为什么我的代码在for循环中执行了3次body?

它不应该只发生两次吗?

为什么是3次?

当我运行这个命令时,我得到:

"4除以2余数是

4除以3余数是

1

4除以4的余数是

循环已退出for循环,因为D现在是5,count现在是2。

if语句中的代码应该已经发生了2次

N的值是4“

public class forIf {

public static void main (String[] args) {

int D;
int N = 4;
int count;

count = 0;

for (D = 2; D <= N; D++) {
  if (N % D == 0)
    count++;
    System.out.println( N + " divided by " + D + " the remainder is");
    System.out.println( N % D );
}
System.out.println("loop has exited out of for loop because D is now " + D);
System.out.println("count is now " + count + ". code inside if statement should've happend " + count + " times");
System.out.println("value of N is "+ N);
}
}
// shouldn't the code inside the if statement only happen twice?
// because N % D is only true twice?
// why is it running that block 3 times?
EN

回答 2

Stack Overflow用户

发布于 2018-09-07 23:00:24

您的if只有一条语句count++。两个print语句不是其中的一部分。您需要将该块封闭在{..}

for (D = 2; D <= N; D++) {
  if (N % D == 0) {
    count++;
    System.out.println( N + " divided by " + D + " the remainder is");
    System.out.println( N % D );
  }
}
票数 0
EN

Stack Overflow用户

发布于 2018-09-07 23:00:58

if (以及whilefor等)的内容超过一行时,需要将它们括在方括号({})中。实际上,您应该始终这样做,即使只有一行,因为这样做更容易阅读,也不容易出现错误。你的if应该是这样的:

for (D = 2; D <= N; D++) {
  if (N % D == 0) {
    count++;
    System.out.println( N + " divided by " + D + " the remainder is");
    System.out.println( N % D );
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52225126

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档