整数数组的备用元素的总和

编程入门 行业动态 更新时间:2024-10-24 18:21:57
本文介绍了整数数组的备用元素的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是的,这个问题似乎很容易。我被要求写一小段代码(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.

更多推荐

整数数组的备用元素的总和

本文发布于:2023-11-29 22:00:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647748.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   数组   总和   元素

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!