gpt4 book ai didi

java - 方法 sum(int, int, int, int) 不适用于参数 (int)

转载 作者:行者123 更新时间:2023-12-02 08:54:43 27 4
gpt4 key购买 nike

Create a method called average that calculates the average of the numbers passed as parameters. The previously created method sum must be used inside this method!

Define the method in the following template:

public static int sum(int number1, int number2, int number3, int number4) {
// you can copy your implementation of the method sum here
}

public static double average(int number1, int number2, int number3, int number4) {
// write your code here
// calculate the sum of the elements by calling the method sum
}

public static void main(String[] args) {
double result = average(4, 3, 6, 1);
System.out.println("Average: " + result);
}

我正在努力将 sum() 方法放入average() 方法中。我不知道如何让它工作,因为我在 eclipse 中不断收到此错误:

The method sum(int, int, int, int) in the type Test066 is not applicable for the arguments (int)
at Test066.average(Test066.java:12)
at Test066.main(Test066.java:5)

这是我的代码:

public class Test066 {
public static void main(String[] args) {
double result = average(4, 3, 6, 1);
System.out.println("Average: " + result);
}

public static int sum(int number1, int number2, int number3, int number4) {
return number1 + number2 + number3 + number4;
}

public static double average(int number1, int number2, int number3, int number4) {
int avg = sum(number1 + number2 + number3 + number4);
}
}

我知道这与我将平均方法定义为 double 类型有关,但我尝试将它们更改为 double 并将我的变量“int avg = ...”调用为“double avg = .. 。”但我仍然遇到同样的错误。我不知道如何将它集中起来,因为我习惯在主方法中调用它,而不是在单独的方法中调用它。

最佳答案

The method sum(int, int, int, int) in the type Test066 is not applicable for the arguments (int)
at Test066.average(Test066.java:12)
at Test066.main(Test066.java:5)

代码中的以下行是罪魁祸首:

int avg = sum(number1 + number2 + number3 + number4);

您的 sum 方法声明表明它接受 4 个整数作为参数。但是当你调用它时,你只传递 1 个参数 - number1 + number2 + number3 + number4 是一个整数,而不是 4。

更正为

int avg = sum(number1, number2, number3, number4);

这样您的代码将开始编译。但它可能不会给你正确的结果。正如其他人所指出的,您需要将总和除以操作数的数量以获得平均值。

int avg = sum(number1, number2, number3, number4) / 4;

此外,平均值将是 float 。因此,您需要进行浮点除法并将其存储在 double 数据类型中以避免截断。

double avg = sum(number1, number2, number3, number4) / 4.0;
return avg;

关于java - 方法 sum(int, int, int, int) 不适用于参数 (int),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60554024/

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