gpt4 book ai didi

java - 如何将命令行参数转换为 double 组以计算总和?

转载 作者:搜寻专家 更新时间:2023-10-31 20:18:12 25 4
gpt4 key购买 nike

所以目前我得到一个“Sum = 0.0”和一个 Mean 等于“NaN”,在与许多再次警告“从 double 到 int 的可能有损转换”的消息作斗争之后。我认为代码最终采用了 double 值,但仍然没有按照我的意愿执行:从命令行获取值,将它们放入数组中,对这些求和,然后计算平均值。

知道错误在哪里吗?

public class StudentMarks{

protected double[] marks;
//create an array filled with double values

public StudentMarks(double[] marks){
this.marks = new double[0]; //set the default array size
}

public void setMarks(){
this.marks = marks;
}

public void getArray(){
//one can only print arrays using loops..
//took me a little to realise that erm.

for(int i=0; i<marks.length; i++)
System.out.println(marks[i]);
}

public double calSum(){

double totals = 0.0;

for(double i: marks) {
//double mLength = Double.parseDouble(marks[i]);
totals+= i;
}
return totals;
}

//A method to calculate the mean of all elements

public double calMean(){
double means = (calSum()/marks.length);
return means;
}

//A main method to test

public static void main(String[] args) {
// Check to see if the user has actually sent a paramter to the method
if (args.length != 7){
System.out.println("Usage: java RandomArray <NUM>. Example: java RandomArray 5");
System.exit(-1);
}

double[] prompt = new double[args.length];
for (int i =0; i<args.length; i++){
prompt[i] = Double.parseDouble(args[i]);
}
StudentMarks test = new StudentMarks(prompt);


test.getArray();

// Calculate the sum of all the values in the array and print it
System.out.println("Sum: "+ test.calSum());

// Calculate the mean of all the values in the array and print it
System.out.println("Mean: "+ test.calMean());
}

}

最佳答案

代替

this.marks = new double[0];

使用

this.marks = marks;

您当前正在将 marks 成员变量分配为零长度数组而不是参数,因此元素之和为零,并且 marks.length为零,所以 calSum()/marks.length0.0/0.0,定义为 NaN

关于java - 如何将命令行参数转换为 double 组以计算总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34227357/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com