gpt4 book ai didi

Java 访问数组中的值

转载 作者:行者123 更新时间:2023-12-02 03:57:24 25 4
gpt4 key购买 nike

我不明白如何访问数组中的数据并将其用作条件,条件是在内容超过4,000,000后停止循环,并且如果其值为偶数则存储并添加该值!

    int[] a=new int[40];
int add=0;
a[0]=1;
a[1]=2;
int i=2;
do{
a[i]=a[i-1]+a[i-2];

System.out.println(a[i]);

if(a[i]%2==0)
{
add=add+a[i];
}
i++;
}
while(i<32);

System.out.println(add);

最佳答案

只需检查变量 add 看看它的值是否大于 4,000,000 并跳出循环。做这样的事情:

if(add > 4000000) {
break;
}

所以你的最终代码将如下所示:

int[] a=new int[40];
int add=0;
a[0]=1;
a[1]=2;
int i=2;
do{
a[i]=a[i-1]+a[i-2];
System.out.println(a[i]);
if(a[i]%2==0){add=add+a[i];}
if(add > 4000000) {
break; //this will get you out of your loop
}
i++;
}while(i<32);
System.out.println(add);

关于Java 访问数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35306662/

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