今天在做书上的题目。。。输出一百以内的素数。。。可是怎么编写都只能输出 不是素数的。。。求解啊。。怎么改动可以解决这个问题。谢谢了。。。对了。才开始学习 java 不知道怎么像 c一样的先声明一个函数 然后 最后在需要的时候再调用 这个声明的函数不在main函数内。
package study.problem.second;
public class promble_2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int n=100;
for (int i=3;i<=n;i++)
{
double sqrti;
sqrti=Math.sqrt(i);
for (int j=2;j<=sqrti;j++)
{
int w=0;
if (i%j==0)
{
System.out.println(i+"is not a Prime ");
break;
}
else
{
}
}
}
}
}
------解决思路----------------------
其实你写的程序是对的。稍微改了下:
public static void main(String[] args) {
// TODO Auto-generated method stub
int n = 100;
for (int i = 3; i <= n; i++) {
double sqrti;
sqrti = Math.sqrt(i);
boolean w = true;
for (int j = 2; j <= sqrti; j++) {
w = true;
if (i % j == 0) {
System.out.println(i + " is not a Prime.");
w = false;
break;
}
}
if(w){
System.out.println(i + " is a Prime!!!");
}
}
}
------解决思路----------------------
public class SuShu {
public static void main(String[] args) {
for (int i = 2; i < 100; i++) {
int j;
for (j = 2; j < (int) (Math.sqrt(i) + 1); j++) {
if (i % j == 0) {
break;
}
}
if (j > (int) Math.sqrt(i)) {
System.out.print(i + " ");
}
}
}
}
------解决思路----------------------
java不需要先声明方法,可以先声明成员变量
package com;
public class Test {
public static void main(String[] args) {
new Test().showsushu();
}
public void showsushu(){
int n = 100;
for (int i = 3; i <= n; i++) {
double sqrti;
sqrti = Math.sqrt(i);
boolean w = true;
for (int j = 2; j <= sqrti; j++) {
w = true;
if (i % j == 0) {
System.out.println(i + " is not a Prime.");
w = false;
break;
}
}
if (w) {
System.out.println(i + " is a Prime!!!");
}
}
}
}