gpt4 book ai didi

java - 计算素数(新手)

转载 作者:行者123 更新时间:2023-12-03 23:01:12 28 4
gpt4 key购买 nike

该程序检查用户输入的数字是否为素数。

我的问题在if语句中。由于某些原因,Boolean永远不会切换。如果数字为质数,则只会给出两个结果。

我想念什么?

import java.util.Scanner;
public class Prime
{

public static void main(String[] args)
{
System.out.println("Enter a number to check if it is prime:");
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
boolean more = true;

do
{
for (int i = 2; i <= n; i++)
{
if (n <=1 || n%i==0)
{
System.out.println(n + " is not prime");
more = false;
}
}
}
while (more);
System.out.println(n + " is prime");
}
}

最佳答案

删除if()内部的打印件,并在do while循环后使用以下代码

if(more)
System.out.println(n + " is prime");
else
System.out.println(n + " is not prime");


并且您也不需要do while循环将其删除。完整代码

 System.out.println("Enter a number to check if it is prime:");
Scanner kb = new Scanner(System. in );
int n = kb.nextInt();
boolean more = true;


for (int i = 2; i <= n / 2; i++) {
if (n <= 1 || n % i == 0) {

more = false;
break;
}
}
if (more) System.out.println(n + " is prime");
else System.out.println(n + " is not prime");


Demo

关于java - 计算素数(新手),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32786291/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com