以文本方式查看主题

-  课外天地 李树青  (http://www.njcie.com/bbs/index.asp)
--  Java程序语言课件  (http://www.njcie.com/bbs/list.asp?boardid=17)
----  程序代码——输出素数  (http://www.njcie.com/bbs/dispbbs.asp?boardid=17&id=1005)

--  作者:admin
--  发布时间:2011/3/13 12:49:03
--  程序代码——输出素数

public class Exec {
        public static void main(String args[]) {
                for (int i = 1; i <= 1000000; i += 2) {
                        boolean flag = true;

                        for (int j = 2; j < Math.sqrt(i); j++) {
                                if (i % j == 0) {
                                        flag = false;
                                        break;
                                }
                        }

                        if (flag)
                                System.out.println(i);
                }

        }
}


--  作者:20-aini
--  发布时间:2011/3/14 17:09:04
--  

public class Esce {
 public static void main(String[] args) {
  int i = 1, j = 2;
  for (i = 1; i < 101; i++) {
   for (j = 2; j < i; j++)
    if (i % j == 0) {
     break;
    } else
     System.out.print(i + " ");

  }
 }

}
为什么把  else  换成   if(i==j) 才对?  

  if(i==j)在这起什么作用??


--  作者:admin
--  发布时间:2011/3/14 17:56:11
--  回复

你的错误来自于排版,请注意格式Ctrl+Shift+F

 

如果是else则与if语句一起作为for的内部子语句

public class Exec {
        public static void main(String[] args) {
                int i = 1, j = 2;
                for (i = 1; i < 101; i++) {
                        for (j = 2; j < i; j++)
                                if (i % j == 0) {
                                        break;
                                } else
                                        System.out.print(i + " ");
                }
        }
}

 

如果是if (i == j)则此语句与for语句同级,不是for的内部子语句

 

public class Exec {
        public static void main(String[] args) {
                int i = 1, j = 2;
                for (i = 1; i < 101; i++) {
                        for (j = 2; j < i; j++)
                                if (i % j == 0) {
                                        break;
                                }
                        if (i == j)
                                System.out.print(i + " ");

                }
        }
}