(C ++) Расчет среднего числа с использованием цикла while

нужна помощь в поиске среднего количества коробок печенья, проданных детьми с помощью счетчика, аккумулятора и конечного стража (базовое программирование, hwk, yay!). У меня проблема с выяснением того, почему AverageBoxes печатает неправильный номер.

Например:

Результат программы выводит -5 средних ящиков, когда это явно не так …

{
int numBoxes,
// Number of boxes of cookies sold by one child
totalBoxes = 0,   // Accumulates total boxes sold by the entire troop
numSeller = 1;    // Counts the number of children selling cookies

double averageBoxes; // Average number of boxes sold per child

// Write code to initialize the totalBoxes accumulator to O and
// The numSeller counter to 1.

cout << "**** Cookie Sales Information ****\n";

// Get the first input
cout << "Enter number of boxes of cookies sold by seller " << numSeller
<< " (or -1 to quit): ";
cin >> numBoxes;

// Write code to start a while loop that loops while numBoxes
// is not equal to -1, the sentinel value.

while(numBoxes != -1)
{
// Write code to add numBoxes to the totalBoxes accumlator.
// Write code to add 1 to the numSeller counter.

totalBoxes += numBoxes;
numSeller++;

// Write code to prompt for and input the number of boxes
// sold by the next seller.

cout << "Enter the number of boxes sold by girl scout # " << numSeller << ": ";
cin >> numBoxes;
}

// When the loop is exited, the value stored in the numSeller counter
// will be one more than the actual number of sellers. So write code
// to adjust it to the actual number of sellers.

numSeller = numSeller - 1;

if(numSeller == 0)       // If true, -1 was the very first entry
cout << "\nNo boxes were sold.\n";
else
{  // Write code to assign averageBoxes the computed average number
// of boxes sold per seller.
// Write code to print out the number of sellers and average number
// of boxes sold per seller.

averageBoxes += numSeller / numBoxes;

cout << "The average number of boxes sold by the " << numSeller << " sellers was " << averageBoxes << endl;
}

return 0;
}

Это, вероятно, легко исправить, но любая помощь будет оценена, спасибо!

-4

Решение

  1. Вы оставили double averageBoxes; неинициализированный (имеет неопределенное значение и делает += это не даст ничего, кроме другой неопределенной ценности).

  2. Вы должны привести любой из операндов (или оба) к типу с плавающей точкой, так что результат numSeller / numBoxes тип с плавающей точкой:

    averageBoxes += numSeller / static_cast<double>(numBoxes);
    

Редактировать:

Хорошо, вы использовали неправильные переменные для выражения выше (это легко сделать благодаря их именам). Так должно быть:

averageBoxes += totalBoxes / static_cast<double>(numSeller);

И, возможно, просто не объявляйте свои переменные в верхней части вашей программы (не давая им значения). Объявите их там, где вы впервые их используете:

// += wasn't needed in any case
double averageBoxes = totalBoxes / static_cast<double>(numSeller);
1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector