![](/img/trans.png)
[英]How can I pick out the odd numbers and even numbers from a given array and then store them in another array?
[英]How to pick out and multiply odd numbers with each other
我是 Java 的初學者。 我的任務是生成 20 個從 60 到 84 的隨機數,然后只挑出奇數並將其相乘並顯示出來。 現在我只能生成數字:
public class Main
{
public static void main(String[] args) {
int[] n = new int[20];
Random rnd = new Random ();
for (int i = 0; i < 20; i++) {
n[i]=rnd.nextInt(84 - 60 + 1) + 60;
System.out.print (n[i]+" : ");
}
}
}
你想把所有的奇數相乘嗎? 您可以存儲結果並檢查生成的數字是否為奇數,然后與結果相乘
public class Main
{
public static void main(String[] args) {
int[] n = new int[20];
Random rnd = new Random ();
long result=1;
for (int i = 0; i < 20; i++) {
n[i]=rnd.nextInt(84 - 60 + 1) + 60;
System.out.print (n[i]+" : ");
if(n[i]%2==1)
result=result*n[i];
}
System.out.print (" Result : " + result);
}
}
您可以使用ThreadLocalRandom
生成 60-84 之間的隨機數,其中包括 min(包括)和 max(不包括)
, 檢查隨機數是否為奇數並將乘法存儲在mul
變量中然后顯示
double mul = 1;
int rand;
for (int i = 0; i < 20; i++) {
rand = ThreadLocalRandom.current().nextInt(60, 85);
if (rand % 2 != 0) {
mul *= rand;
}
}
System.out.println("The multiply of odd numbers between [60-84]: " + mul);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.