【问题标题】:how to get average using for loop in java? [duplicate]如何在java中使用for循环获得平均值? [复制]
【发布时间】:2021-06-04 19:29:41
【问题描述】:

问题是:使用循环从键盘中取出 10 个整数并在屏幕上打印它们的平均值。

在java中使用for循环时如何获得平均值

这是我尝试过的:

Scanner sc = new Scanner(System.in); 
int sum = 1; 
for (int i=1; i<=10; i++ ) { 
    System.out.println("Enter number "); 
    sum = sum + sc.nextInt(); 
    int avg = sum/10; 
}
System.out.println("sum is "+ sum); 
System.out.println("Avg is : "+ avg);

【问题讨论】:

  • 你在正确的轨道上。但是:1)为什么sum从1开始?从开始不是更有意义吗? 2) 无需每次循环计算avg;只有一次 after 循环很好,并避免了 avg 变量的 scope 问题。
  • 这段代码还能编译吗?

标签: java


【解决方案1】:

这里是完整的代码和 cmets,以防你不理解代码


/**
 * This class is built and tested in java version 15.0.2
 * @since 15.0.2
 */
public class AverageDemo {
    public static void main(String[] args) {
        //Array size. you can change this size whatever you want
        //for the array
        int size = 10;
        //Declare a integer number array. You can also use List<Integer>
        int[] num = new int[size];
        System.out.println("Insert 10 integer numbers:");
        //use Scanner class for better data input. Make sure it imported in java.util.Scanner
        Scanner scanner = new Scanner(System.in);

        //start a loop for insert the numbers
        //the array will start counting from num[0] -> num[size - 1] so condition i <= size will
        //throws a exception
        for (int i = 0; i < size; i++) {
            System.out.print("num["+i+"]=");
            num[i] = scanner.nextInt();
        }

        //If you want to test whether the array is fully inserted.
        //Remove these commented lines
        
        // for (int i = 0; i < size; i++) {
        //    System.out.println(num[i]);
        // }
        
        System.out.println(average(num, size));
        
    }
    
    //Helper method for average calculating
    //the rule is average equals total of all integer numbers divides with how much numbers in numbers list
    
    private static double average(int[] num, int size) {
        int total = 0;
        for (int i = 0; i < size; i++) {
            total += num[i];
        }
        
        return (double)total / size;
    }
}

【讨论】:

  • 哦,我看到了这个错误!应该是total += num[i]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-22
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多