有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在java中计算总和?

我需要写一个代码,插入10个等级,然后得到这10个等级的平均值。我知道怎么做,只是我不知道怎么计算所有成绩的总和。我在该网站上发现以下代码:

public int sumAll(int... nums) { //var-args to let the caller pass an arbitrary number of int

int sum = 0; //start with 0

    for(int n : nums) { //this won't execute if no argument is passed
        sum += n; // this will repeat for all the arguments
    }
    return sum; //return the sum
} 

所以我写了这样的代码,它成功了!:

import java.util.Scanner;

public class Loop7 {

    public static void main(String[] args) {

        Scanner scan = new Scanner (System.in);
        System.out.println("Please enter how many grades you want to insert : ");
        int num1 = scan.nextInt();
        int num;
        double sum =0;
        for(int i= 0; i<num1; i++)
        {
            System.out.println("Please enter a grade: ");
            num = scan.nextInt();
            sum += num;
        }
        System.out.println("the average is: "+(sum)/num1);

    }

所以我的问题是sum+=num;意思是那一行给了我多少钱?为什么我要写双和=0


共 (3) 个答案

  1. # 1 楼答案

    在这里,我解释每一行代码,以更好地帮助您理解这段代码

    public class Loop7 {
    
        public static void main(String[] args) {
    
            Scanner scan = new Scanner (System.in); //this is what allows the user to input their data from the console screen
            System.out.println("Please enter how many grades you want to insert : "); //this just outputs a message onto the console screen
            int num1 = scan.nextInt(); //This is the total number of grades the user provides and is saved in the variable named num1
            int num; //just a variable with nothing in it (null)
            double sum =0; //this variable is to hold the total sum of all those grades
            for(int i= 0; i<num1; i++) //loops as many times as num1 (if num1 is 3 then it loops 3 times)
            {
                System.out.println("Please enter a grade: "); //output message
                num = scan.nextInt(); //every time the loop body executes it reads in a number and saves it in the variable num
                sum += num; //num is then added onto sum (sum starts at 0 but when you add 3 sum is now 3 then next time when you add 1 sum is now 4 and so on)
            }
            System.out.println("the average is: "+(sum)/num1); //to get the average of a bunch of numbers you must add all of them together (which is what the loop is doing) and then you divide it by the number of items (which is what is being done here)  
    
        }
    
  2. # 2 楼答案

    你需要写作的原因

    double sum = 0.0; 
    

    因为你需要先初始化总和。下一个

    sum += num;
    

    意味着

    sum = sum + num;
    

    用一种更简单的方式

  3. # 3 楼答案

    sum += num;意味着声明为0的sum被添加了从控制台获得的num。所以你只需要做这个:sum=sum+num;为周期。例如,总和是0,然后你加5,它变成sum=0+5,然后你加6,它变成sum = 5 + 6,依此类推。它是双倍的,因为你使用除法