整数数组的备用元素的总和 [英] Sum of alternate elements of integer array

查看:75
本文介绍了整数数组的备用元素的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是的,这个问题似乎很容易。我被要求写一小段代码(Java),以找出整数数组的替代元素的总和。起始位置将由用户指定。例如,如果用户输入3作为起始位置,求和模块将从索引(3-1 = 2)开始。我的目标是不完成我的家庭作业或东西,而是了解为什么我的代码不起作用。因此,如果有人可以指出并建议解决方案?代码如下:

Yes, the problem seems rather easy. I was asked to write a small piece of code (Java) that finds out the sum and average of alternate elements of integer array. The starting position will be given by the user. For example, if the user inputs 3 as the starting position, the sum module will start from index (3-1= 2). My objective is to not complete my homework or stuff, but to learn why my code is not working. So if anyone could point out please and suggest fixes? Here's the code:

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); 

   }
 }
}


推荐答案

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

In your calc method, you got the for loop definition right (i.e. the initial value, the condition and the increment are all correct), but inside the loop, the sum calculation is wrong. In each iteration, you should add the current element - ar[i] - to the total 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

This would only be correct if the average is on all elements. Since the average is on half the elements, you shouldn't divide by ar.length.

这篇关于整数数组的备用元素的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆