[英]Sum of alternate elements of integer array
是的,這個問題似乎很容易。 我被要求寫一小段代碼(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);
}
}
}
在您的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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.