繁体   English   中英

如何在Java中计算总和?

[英]How to calculate sum in 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?

在这里,我将解释每行内容,以更好地帮助您理解此代码。

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)  

    }

sum += num; 意味着将声明为0的sum与从控制台获取的num相加。 因此,您只需执行以下操作: sum=sum+num; 为周期。 例如,sum为0,然后加5,即为sum=0+5 ,然后加6则为sum = 5 + 6 ,依此类推。 它是双重的,因为您正在使用除法。

你需要写的原因

double sum = 0.0; 

因为您需要先初始化和。 接下来的

sum += num;

手段

sum = sum + num;

只是以更简单的方式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM