[英]Finding MAX even and odd values in an array
我需要找到給定數組的 MAX 偶數值和奇數值。 在這種情況下,我需要控制台打印最大偶數為 8,最大奇數為 11 這是從另一個問題修訂的,因為提問的冷卻時間
import java.util.Scanner;
public class Question03 {
public static int[] array;//The array to be used in the problem
public static void main(String[] args) {
int number;//Used for the stairs
if(args == null || args.length == 0)
{
int[] tempArray ={2,4,6,8,11};//You may change these values to test
array = tempArray;
}
else
{
}
//Write your solution here
int evenMax = array[0];
int oddMax = array[0];
for (int x =1; x<array.length; x++){
if(evenMax %2 == 0)
{
if (evenMax<array[x])
{
}
}
if(oddMax<array[x]){
oddMax=array[x];
}
}
System.out.println("The largest number is: " + evenMax + ". The smallest number is: " +oddMax);
您可以將 Java 8 中的 Streams 與 Optional 一起使用:
import java.util.Arrays;
public static void main(String[] args) {
int[] array = {1,2,3};
Arrays
.stream(array)
.filter(n -> n > 0)
.average()
.getAsDouble();
}
只是修復您的代碼,我添加了一個變量來存儲計算平均值時應用作除數的元素數量。 在這種情況下, total
存儲數組中所有元素的總和。
int elements = array.length;
double total = 0;
for(int i=0; i<array.length; i++)
{
if(array[i] < 0)
{
array[i] = 0;
}
if(array[i] == 0)
{
elements--;
}
total += array[i];
}
double average = total / elements;
System.out.println("the average was " +average);
PS 作為任何算法,有很多方法可以解決這個問題。 但是,在這里,我的意圖是根據您的想法來幫助您。
這樣的事情怎么樣:
double total = 0;
int count = 0;
for(int i=0; i<array.length; i++)
{
if(array[i] > 0)
{
total += array[i];
++count;
}
}
double average = total / count;
System.out.println("the average was " +average);
甚至:
double total = 0;
int count = 0;
for(double value: array)
{
if(value > 0)
{
total += value;
++count;
}
}
double average = total / count;
System.out.println("the average was " +average);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.