我一直在尝试制作一个计算9个数字平均值的基本计算器。问题是它总是跳过最后一行。 我的代码:
/* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package avarage.calc;
import java.util.Scanner;
/**
*
* @author taine
*/
public class AvarageCalc {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner(System.in);
double num1;
double num2;
double num3;
double num4;
double num5;
double num6;
double num7;
double num8;
double num9;
double num10;
double ans;
System.out.print("Enter Number #1:");
num1 = input.nextDouble();
System.out.print("Enter Number #2:");
num2 = input.nextDouble();
System.out.print("Enter Number #3:");
num3 = input.nextDouble();
System.out.print("Enter Number #4:");
num4 = input.nextDouble();
System.out.print("Enter Number #5:");
num5 = input.nextDouble();
System.out.print("Enter Number #6:");
num6 = input.nextDouble();
System.out.print("Enter Number #7:");
num7 = input.nextDouble();
System.out.print("Enter Number #8:");
num8 = input.nextDouble();
System.out.print("Enter Number #9:");
num9 = input.nextDouble();
ans = num1 + num2 + num3 + num4 + num5 + num6 + num8 + num9;
System.out.println("The Average of the numbers you gave is:" + ans / 9);
}
}
程序运行时:
run:
Enter Number #1:20
Enter Number #2:20
Enter Number #3:20
Enter Number #4:20
Enter Number #5:20
Enter Number #6:20
Enter Number #7:20
Enter Number #8:20
Enter Number #9:20
The Average of the numbers you gave is:17.77777777777778
BUILD SUCCESSFUL (total time: 10 seconds)
答案 0 :(得分:3)
您的平均值不正确,因为您的金额中缺少num7
ans = num1 + num2 + num3 + num4 + num5 + num6 + num8 + num9;
应该是
ans = num1 + num2 + num3 + num4 + num5 + num6 + num7 + num8 + num9;
答案 1 :(得分:1)
num7
变量。做这样的事情可能会更好:
double ans = 0;
Scanner input = new Scanner(System.in);
int x = 9 //Or some other number
for(int i = 1; i <= x; i++){
System.out.print("Enter Number #" + i);
ans += input.nextDouble();
}
System.out.println("The Average of the numbers you gave is:" + ans / x);
现在,如果您需要计算20个元素的平均值,您只需将x
的值设置为20
。