我在命令行中使用以下代码在命令行中编译代码:
java aac 2 4 6 8 10
我得到了结果:
5
位置0的数字是2.0
总和是:2.0位置1的数字是4.0
总和是:4.0位置2的数字是6.0
总和是:6.0位置3的数字是8.0
总和是:8.0位置4的数字是10.0
总和是:10.0
我想要实现的是,sum
是所有数字的总和除以数字的数量,但是对于数量,我有一个长度变量。对于此示例,长度在开始时显示为5。
public class aac {
public static void main(String args[]) {
// working out the length
int length = args.length;
System.out.println(length);
// this is a for loop that repeats until integer i is greater than
// integer length, which is the length of the args String array.
for (int i = 0; i < length; i++) {
// this string equals whatever value is in position i in string array args
String all = args[i];
// integer numConvert now equals the integer of String all
double numConvert = Double.parseDouble(all);
System.out.print("The number in position " + i + " is " + " ");
System.out.println(numConvert);
double sum = 0;
sum = sum += numConvert;
System.out.println("The Sum is: " + sum);
System.out.println();
}
}
}
答案 0 :(得分:0)
为了计算平均值,您是否在创建总和方面遇到问题?如果是这样,请将double sum = 0;
移出for循环。在循环之后,您将其除以args.length
,这将是您的平均值。
答案 1 :(得分:0)
这里有一点改进你的代码:
double average = 0.0;
double sum = 0;
for(int i = 0; i < length; i++){
String all = args2[i];
double numConvert = Double.parseDouble(all);
System.out.print("The number in position "+i+" is ");
System.out.println(numConvert);
sum += numConvert;
average = sum / (i+1);
System.out.println("The Sum is: "+sum);
System.out.println("The average is :" + average);
System.out.println();
}
我在double
循环之外创建了2个for
变量。
每次循环时,都会将当前值添加到sum
变量中以获得总和。
此外,average
更改为sum
的值除以我们已经看过的数字。
这是输出:
5
The number in position 0 is 2.0
The Sum is: 2.0
The average is :2.0
The number in position 1 is 4.0
The Sum is: 6.0
The average is :3.0
The number in position 2 is 6.0
The Sum is: 12.0
The average is :4.0
The number in position 3 is 8.0
The Sum is: 20.0
The average is :5.0
The number in position 4 is 10.0
The Sum is: 30.0
The average is :6.0