我需要编写一个代码,您可以在其中插入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?
答案 0 :(得分: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)
}
答案 1 :(得分:0)
from .models import KPIReport, KPI_CHG
@admin.register(KPI_CHG)
class KPI_CHGAdmin(admin.ModelAdmin):
list_display = ('Date','Item_SKU','Account','Country','Sessions','Session_Pct','Page_Views','Page_Views_Pct','Buy_Box_Pct','Units_Ordered','Unit_Session_Pct','Ordered_Product_Sales','Total_Order_Items','Sales_Rank','Actual_Sales','Selling_Price','Reviews','Camel', 'Notes')
list_filter = (('Date', DateRangeFilter),'ItemSKU','Country')
search_fields = ('Date','ASIN','ItemSKU','Country','Selling_Price')
list_editable = ('Notes',)
表示您声明为0的sum += num;
添加了sum
,您可以从控制台获取该num
。所以你只需要这个:sum=sum+num;
进行循环。例如,sum为0,然后添加5,它变为sum=0+5
,然后添加6,它变为sum = 5 + 6
,依此类推。它是双倍的,因为你使用的是分裂。
答案 2 :(得分:0)
您需要写信的原因
double sum = 0.0;
是因为您需要先初始化和。接下来
sum += num;
表示
sum = sum + num;
只是更简单的方法。