gpt4 book ai didi

Java 数组中接下来的 10 个偶数

转载 作者:行者123 更新时间:2023-12-01 18:01:10 25 4
gpt4 key购买 nike

我必须使用数组来解决大学的一个问题,就是这样:

编写一个 Java 程序,该程序将创建一个大小为 10 的数组,并将前 10 个大于给定用户输入的偶数放入其中。

这就是我正在尝试的,但我无法获得正确的输出

import java.util.Scanner;
public class EvenNumbers
{
public static void main (String args[])
{
Scanner scan = new Scanner(System.in);
int array[]=new int[10];

System.out.println("Please enter a number:");
int num = scan.nextInt();
num+=1;
int i=0;

while(i<10)
{
if(num/2==0)
{
array[i]=num;
num++;
i++;
}
else
num++;
}



for(int j=0; j<array.length; j++)
{
System.out.print(array[j]);
}
}
}

最佳答案

您应该检查num%2==0而不是num/2==0

您还可以通过仅迭代偶数来简化程序:

num++;
if (num % 2 == 1) // make sure that num is even
num++;

for(int i = 0; i < 10; i++)
{
array[i] = num;
num += 2; // jump to the next even number
}

关于Java 数组中接下来的 10 个偶数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40791379/

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