c++ - C++ cout 错误地输出 0
问题描述
出于某种原因,这个代码块错误地给出了零,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。
推荐阅读
- node.js - 无法在 webstorm 上安装 web3(在 mac 上)
- python - 如何使用 model.getVars() 获取 tupledict 对象?
- java - 在 Java 8 中的标识字段上查找数组列表的子集
- html - iOS Chrome 计算错误的文档高度
- javascript - 推入 react native 的 typescript
- api - 我在进行身份验证时没有在 LinkedIn oauth 2.0 中获得刷新令牌。谁能解释一下?
- r - 是否有使用 MuMin 的疏通功能解决 glmmTMB 模型中不收敛的解决方法?
- .net - dotnet core 加密和 sql server 解密
- html - 溢出:滚动离开其父元素的元素
- angular - Angular(Ionic) 服务和模型依赖