首页 > 解决方案 > 无法从函数内的数组中提取信息以打印直方图(C++)

问题描述

我正在尝试根据放入数组中的值打印直方图。我觉得我很接近,但我无法从存储在创建直方图数组(bin)的直方图函数中的数组中提取信息。

标准偏差也被计算出来,但这不是我遇到的问题。感谢您的时间。

这是我的代码:

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

double mean(int size, int* numbers); 
double sDeviation(int numOfScores, int average, int* scores);
int* histogram(int numOfScores, int* scores);//<<Here is the call to the histogram function

int main()
{
int count = 0;
int scores[100];

while (true)
{
    int scoreToBeEntered;
    cout << "Please enter a score between 0 and 109: ";
    cin >> scoreToBeEntered;

    if(scoreToBeEntered < 0)
        cout << "No value entered" << endl;
    else if(scoreToBeEntered != -1)
        scores[count++] = scoreToBeEntered;
    else
        break;
}

for(int i = 9; i >= 0; i--)//Here is where the issue starts
{   
    cout << i << "|" << endl;
    for (int k = 0; k < bin[i]; k++) 
    {
        cout << '*'; 
    }
    cout << endl;//<< This is the chunk of code where I think the issue is. 
}

cout << "SD: " << sDeviation(count, mean(count, scores), scores) << endl;

system("pause");
return 0;
}

int* histogram(int numOfScores, int* scores)
{
int* bin = new int[10];
for(int i = 0; i < numOfScores; i++)
    if(scores[i] >= 90)
    {
        bin[9]++;
    }
    else if (scores[i] >= 80 && scores[i] < 90)
    {
        bin[8]++;
    }
    else if (scores[i] >= 70 && scores[i] < 80)
    {
        bin[7]++;
    }
    else if (scores[i] >= 60 && scores[i] < 70)
    {
        bin[6]++;
    }
    else if (scores[i] >= 50 && scores[i] < 60)
    {
        bin[5]++;
    }
    else if (scores[i] >= 40 && scores[i] < 50)
    {
        bin[4]++;
    }
    else if (scores[i] >= 30 && scores[i] < 40)
    {
        bin[3]++;
    }
    else if (scores[i] >= 20 && scores[i] < 30)
    {
        bin[2]++;
    }
    else if (scores[i] >= 10 && scores[i] < 20)
    {
        bin[1]++;
    }
    else if (scores[i] >= 0 && scores[i] < 10)
    {
        bin[0]++;
    }

    return bin; 

}   


double sDeviation(int numOfScores, int average, int* scores)
{
double deviation = 0;

for (int i = 0; i < numOfScores; i++)
    deviation += pow(scores[i] - average, 2);

return sqrt(deviation / numOfScores);
}

double mean(int size, int* numbers)
{
double sum = 0;

for (int i = 0; i < size; i++)
    sum += numbers[i];

return sum / size;
}

这是我的代码之后应该产生的输出。

案例 1:100、95、90、85、80、75、70、65、60、40、20 和 5。

9| ***
8| **
7| **
6| **
5|
4| *
3|
2| *
1|
0| *

标签: visual-c++

解决方案


推荐阅读