gpt4 book ai didi

Java - 根据用户输入创建数组

转载 作者:行者123 更新时间:2023-12-01 22:04:12 24 4
gpt4 key购买 nike

这是作业:

  1. Create an array to store 10 numbers.
  2. Using a loop, prompt the user to enter 10 grades and store them in the array.
  3. Then make another loop that prints the numbers in the array out backwards and adds up the numbers in the array.
  4. Use the sum to calculate the average of the numbers. Print out the average of the numbers.

到目前为止我的代码:

public static void ar() {

double[] grades = new double[10];
Scanner kb = new Scanner(System.in);

for(int i=0; i < grades.length; i++)
grades[i]=kb.nextDouble();

double sum=0;

for(int j=10; j > grades.length; j--)
sum=sum+grades[j];

double ave = sum/10;

System.out.println(ave);
}

但是它只打印 0.0 十次。

最佳答案

for 循环中向后迭代的界限是错误的。您的意思是使用 for (int j=10; j>=0; j--)。试试这个代码:

public static void ar() {
double[] grades = new double[10];
Scanner kb = new Scanner(System.in);
for (int i=0; i<grades.length; i++)
grades[i] = kb.nextDouble();

double sum = 0;

for (int j=grades.length-1; j>=0; j--)
sum = sum + grades[j];

double ave = sum / 10;
System.out.println(ave);
}

关于Java - 根据用户输入创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33093553/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com