简体   繁体   English

对用户确定的int量求和,然后将结果除以它们的总量

[英]Sum a user determined amount of int and divide the result on their total amount

I am in the first week of my Java studies and I have to make a program that sums an user defined amount of numbers and then divide them to the amount of numbers given(average value).Then the user has to input the numbers separately one by one and the program has to put them in order when asking(Number 1: ; Number 2: ; etc). 我正处于Java学习的第一周,我必须制作一个程序来对用户定义的数字量求和,然后将它们除以给定的数字量(平均值),然后用户必须分别输入一个数字一位时,程序必须按顺序排列它们(数字1 :;数字2:等)。 The thing is that I can only use loops: for, while; 问题是我只能使用循环:for,while, conditions: if ;switch and util.Scanner ! 条件:if; switch和util.Scanner! No arrays no packages no other functions :(. 没有数组没有包没有其他功能:(。

First thing I thought was this but on every loop the value of the variable changes and there is no way to sum with the next/previous value. 我首先想到的是这个,但是在每个循环中,变量的值都会更改,并且无法求和下一个/上一个值。

    import java.util.Scanner;
        Scanner in= new Scanner(System.in);
        for(count=1;count<=numberAmount;count++){
            System.out.println("Number"+count+" :");
            int number=Integer.parseInt(in.nextLine());
        }
    }
}

If you are not required to print back each of the number entered, then you can just sum it everytime user enter the number. 如果不需要打印回每个输入的数字,则每次用户输入数字时都可以对其求和。

Scanner in= new Scanner(System.in);
System.out.println("How many number?")
int numberAmount = Integer.parseInt(in.nextLine());
int sum=0;
int average=0;

for(count=1;count<=numberAmount;count++){
    System.out.println("Number"+count+" :");
    sum+=Integer.parseInt(in.nextLine());
}

average = sum / numberAmount;
System.out.println("The average of " +numberAmount+" entered number(s) is "+average);
import java.util.Scanner;
Scanner in= new Scanner(System.in);
int number = 0;
for(count=1;count<=numberAmount;count++){
    System.out.println("Number"+count+" :");
    number += Integer.parseInt(in.nextLine());
}
}
} 

Declare the variable outside the loop to use as sum 在循环外声明变量以用作总和

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

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