【问题标题】:histogram with dynamic array具有动态数组的直方图
【发布时间】:2013-06-20 20:16:27
【问题描述】:

我要做的问题如下。

编写一个程序,输出学生作业成绩的直方图。程序应将每个学生的成绩作为整数输入并存储在向量中。应输入成绩,直到用户输入 -1 作为成绩。然后程序应扫描向量并计算直方图,等级的最小值为 0,但您的程序应确定用户输入的最大值。使用动态数组来存储直方图。将直方图输出到控制台。

添加了一个例子: 输入 20 30 4 20 30 30 -1 输出 4 的数量:1 20 的数量:2 30 的数量:3

到目前为止,我编写的代码如下:

#include <iostream>
#include <vector>

using namespace std;

void histogram(vector<int> input);
int main()
{
    int i=0;
    int value;
    vector<int> grades;
    while(i>=0)
    {
        cout<<"Enter a grade for the student: ";
        cin>>value;
        grades.push_back(value);
        if((grades[i])==(-1))
        {
            break;
        }
        i++;
    }
    histogram(grades);


}

void histogram(vector<int> input)
{

}

我确实为直方图函数尝试了一些东西,但它以可怕的方式失败了。我不知道如何处理这个直方图。

【问题讨论】:

    标签: histogram dynamic-arrays


    【解决方案1】:

    不知道这是否正确,但我这样做了。

    void histogram(vector<int> input)
    {
        // declaration of a new array
        int aGrades[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};         
    
    
        for (std::vector<int>::iterator it = input.begin() ; it != input.end(); ++it)
        {
            int number = *it;
            //cout << number << endl;
            aGrades[number] += 1;
            //int *it; //works fine
        }
    
        for (int gradeLoop = 0; gradeLoop < 100; gradeLoop++)
        {
            if(aGrades[gradeLoop] > 0 )
            {
                cout << "Number of " << gradeLoop << "'s:   " << aGrades[gradeLoop] << endl;
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-09
      • 2011-10-21
      • 1970-01-01
      • 2020-07-17
      • 1970-01-01
      • 2017-04-23
      • 1970-01-01
      • 2013-06-14
      相关资源
      最近更新 更多