繁体   English   中英

C++ cout 错误地输出 0

[英]C++ cout outputting 0 incorrectly

出于某种原因,这个代码块错误地将零作为cout ,尽管它是不正确的。

// HouseholdSize.cpp - This program uses a bubble sort to arrange up to 300 household sizes in
// descending order and then prints the mean and median household size. 
// Input:  Interactive.
// Output:  Mean and median household size. 

#include <iostream>
#include <string>
using namespace std;

int main() 
{
   // Declare variables.
        
   const int SIZE = 300;    // Number of household sizes
   int householdSizes[SIZE];    // Array used to store 300 household sizes
   int x; 
   int limit = SIZE;
   int householdSize = 0;
   int pairsToCompare;
   bool switchOccurred; 
   int temp;
   double sum = 0;
   double mean = 0;
   double median = 0;

   // Input household size      
   cout << "Enter household size or 999 to quit: ";
   cin >> householdSize;
   
   // This is the work done in the fillArray() function
   x = 0;
   while(x < limit && householdSize != 999)   
   {
      // Place value in array.
      householdSizes[x] = householdSize;
      // Calculate total of household sizes
      
      x++;    // Get ready for next input item.
      cout << "Enter household size or 999 to quit: ";
      cin >> householdSize;
   }  // End of input loop.
        
   
   // Find the mean
   mean = sum/limit;

cout<<"Mean: "<<mean; 

   
   // This is the work done in the sortArray() function

   // This is the work done in the displayArray() function
 
 // Print the mean

   // Find the median
   
   // Print the median
for(int i = 0; i<limit; i++) {

  for(int j = i+1; j<limit; j++){

     if(householdSizes[j] < householdSizes[i]){

        temp = householdSizes[i];

        householdSizes[i] = householdSizes[j];

        householdSizes[j] = temp;       }    } }

median= (householdSizes[(limit-1)/2]+householdSizes[1+(limit-1)/2])/2.0;

if((limit - 1)%2==0){

   median = householdSizes[limit/2];

}

cout<<endl<<"Median: "<<median; 

            
   return 0;
} // End of main function


中位数似乎是正确的,但是对于平均值,您将总和初始化为 0,但没有将其递增,因此mean = sum/limit; 永远是0。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM