Да, я знаю, что здесь есть много способов. Это часть задания. В этом коде все работает по назначению, за исключением того, что при вводе чисел, равных сумме < = 100, «средний» выход неверен. Например: если я поставил 8,10,19 и ноль, чтобы выйти из выхода, то счет 3 сумма 37 средний 9,25 .... среднее должно быть 12.3333. Теперь, если я вхожу в 8, 10, 99, вывод равен 3 суммам 117 и среднему 39, что является правильным. Почему он работает на сумму> 100, но не сумма < = 100 ??? Я не понимаю. Что мне не хватает?что не так с моим методом для avg?
public static void main(String[] args) {
//Use Main Method for gathering input
float input = 1;
// Declare variable for sum
float theSum = 0;
// Declare variable for average
float average = 0;
// Declare variable for counting the number of user inputs
int counter = 0;
/* Initialize the while loop using an input of 0 as a sentinel value
* to exit the loop*/
while (input != 0) {
if (input!=0){
counter++;
}
input = Float.parseFloat(
JOptionPane.showInputDialog(
null, "Please enter a number. Enter 0 to quit: "));
// Invoke sum method and pass input and summation to sum method
theSum = (sum(input, theSum));
if (theSum > 100)
{
JOptionPane.showMessageDialog(null, "The sum of your numbers "
+ "are greater than 100!");
break;
}
}
// Invoke display method and pass summation, average, and counter variables to it
average = (avg(theSum, counter));
display(theSum, average, counter);
}
public static float sum(float num1, float sum) {
//Add the user's input number to the sum variable
sum += num1;
//Return value of sum variable as new summation variable
return sum;
}
public static float avg(float num1, float num2) {
//Declare and initialize variable for average
//Calculate average
float average = num1/num2;
//Return value of average variable
return average;
}
public static void display(float sum, float average, int counter) {
/* I am subtracting 1 from variable counter so as not to include the sentinel value
* of 0 that the user had to enter to exit the input loop in the overall count*/
// Display the count, sum, and average to the user
if (sum > 100) {
JOptionPane.showMessageDialog(null, "Count = " + (counter) + ", Sum = " + sum + ", Average = " + average);
}
if (sum <= 100) {
JOptionPane.showMessageDialog(null, "Count = " + (counter - 1) + ", Sum = " + sum + ", Average = " + average);
}
}
}
Почему вы используете отдельные методы для основных арифметических операторов? – chrylis
Да. Обычно средний метод принимает массив или ArrayList чисел, а затем вычисляет среднее из них. –
Это было требование задания. На этой неделе мы изучили методы, вы можете сказать? :) – Chris