2015-11-15 9 views
-4

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

Например:

Program result prints out -5 averageBoxes when that's clearly not right...

{ 
    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; 
} 

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

+1

Можете ли вы поделиться примером ввода, вывода, который вы получаете, и вывода, который вы ожидаете? – Mureinik

+0

Привет, вывод, который я получаю, должен находиться в ссылке выше, в разделе «Пример:» Результат, который я ожидаю, должен сказать, что «Среднее количество ящиков, проданных 5 продавцами, было 39,8» – Frankie

+0

Ваша окончательная математика уравнение неверно. Измените 'averageBoxes + = numSeller/numBoxes;' на 'averageBoxes = totalBoxes/numSellers;' –

ответ

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

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

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

Edit:

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

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

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

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

Есть ли какая-то особая причина, почему нам нужно было установить static_cast 'numSeller' и totalBoxes? – Frankie

+0

Нет, нет. Делайте, как хотите. – LogicStuff

 Смежные вопросы

  • Нет связанных вопросов^_^