public static void evenSumMax(Scanner console){
System.out.print("How many integers?");
int a=console.nextInt();
int sum=0;
for(int i=1;i<=a;i++){
System.out.print("Next integer?");
int v=console.nextInt();
if(i%2==0){
sum=sum+v;
}else{
}
}
System.out.println("Sum of even is "+sum);
}
以及如何在for循环中找到最大偶数?
我需要编写System.out.print(“maximum even is”+ ????);
答案 0 :(得分:1)
您可以尝试使用以下代码:
public static void evenSumMax(Scanner console){
System.out.print("How many integers?");
int a=console.nextInt();
int maxEven = 0;
for(int i=1;i<=a;i++){
System.out.print("Next integer?");
int v=console.nextInt();
if(v%2==0){
if(v > maxEven)
maxEven = v;
}
}
System.out.println("Maximum even is " + maxEven);
}
答案 1 :(得分:0)
您可以使用:(添加到现有代码中)
public static void evenSumMax(Scanner console) {
System.out.print("How many integers?");
int a = console.nextInt();
int sum = 0;
int max = Integer.MIN_VALUE; // the smallest value possible in 32-bit integer
for (int i = 1; i <= a; i++) {
System.out.print("Next integer?");
int v = console.nextInt();
// assuming you're looking for max odd number in input numbers
if (v % 2 == 0 && v > max) {
max = v;
}
if (i % 2 == 0) {
sum = sum + v;
} else {}
}
System.out.println("Sum of even is " + sum);
System.out.print("maximum even is "+ max);
}
答案 2 :(得分:0)
以下内容有效。检查输入值的条件后,将其添加到sum变量并将其与maxInt进行比较。如果输入的数字大于先前输入的数字,则将maxInt设置为新值。
public static void evenSumMax(Scanner console){
System.out.print("How many integers?");
int a=console.nextInt();
int sum=0;
int maxInt=0;
for(int i=0;i<a;i++)
{
System.out.print("Next integer?");
int v=console.nextInt();
if(v%2==0){
sum=sum+v;
if(maxInt<v){
maxInt=v;
}
}
}
System.out.println("Sum of even is "+sum);
System.out.println("Maximum even number is "+maxInt);
}