整数数组的替代元素的总和(Sum of alternate elements of integer

2019-10-21 13:41发布

是的,这个问题似乎相当容易。 我被要求写一小块代码(Java)的那找出整数数组的替代元素的总和和平均。 起始位置将由用户给出。 例如,如果作为起始位置的用户输入3,总和模块将从索引(3-1 = 2)启动。 我的目标是没有完成我的家庭作业或东西,而是要了解为什么我的代码不能正常工作。 因此,如果任何人都可以指出,请和建议修复? 下面的代码:

import java.util.Scanner;
public class Program {

static int ar[]; static int sum = 0; static double avg = 0.0;
static Scanner sc = new Scanner(System.in);
public Program(int s){
    ar = new int[s];
}
void accept(){
    for (int i = 0; i<ar.length; i++){
        System.out.println("Enter value of ar["+i+"] : ");
        ar[i] = sc.nextInt();
    }
}
void calc(int pos){
    for (int i = (pos-1); i<ar.length; i+=2){
        sum = ar[i] + ar[i+1];
    }
}
public static void main(String[] args){
    boolean run = true;
    while (run){
    System.out.println("Enter the size of the array: ");
    int size = sc.nextInt(); 
    Program a = new Program(size);
    a.accept(); 
    System.out.println("Enter starting position: "); int pos = sc.nextInt(); //Accept position
    if (pos<0 || pos>ar.length){
        System.out.println("ERROR: Restart operations");
        run = true;
    }
    a.calc(pos); //Index = pos - 1; 
    run = false; avg = sum/ar.length;
    System.out.println("The sum of alternate elements is: " + sum + "\n and their average is: " + avg); 

   }
 }
}

Answer 1:

在你的calc方法中,你得到的for循环定义权(即初始值,条件和增量都是正确的),但在循环内,该sum的计算是错误的。 在每次迭代中,你应该添加当前元素- ar[i] -总sum

for (int i = (pos-1); i<ar.length; i+=2){
    sum = sum + ar[i]; // or sum += ar[i];
}

您还可以在平均计算的错误:

avg = sum/ar.length;

如果平均是所有元素这只会是正确的。 由于平均上一半的元素,你不应该被划分ar.length



文章来源: Sum of alternate elements of integer array
标签: java arrays sum