簡體   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