直方图程序辅助

时间:2013-04-05 15:00:11

标签: c++

我对我的程序有点困惑,该程序是读取一组结果,然后构建一个直方图,指示每十年中有多少标记,即10-20之间有多少标记等。

我有2个问题

  1. 如何编辑我的代码,只允许readExamResults存储范围为0 -100
  2. 的代码
  3. 如何让PrintHisto在某个setw()上打印*,这取决于每个结果在哪个十年。如果我进入3,4,5,11,23它应该在< 10十年中显示3 *,在10-20十年中显示1,在20-30十年中显示1。
  4. 任何帮助将不胜感激。

    代码:

    using namespace std;
    
     void readExamMarks(int examMarks[], int sizeOfArray){
    
    cout << "Please enter a set of exam marks to see a histogram for:" << endl;
    int x = 0;
    for( int idx = 0; idx < sizeOfArray; idx++){
    
        cin >> x;
        examMarks[idx] = x;
    }
    }
    
    void printExamMarks(int examMarks[], int sizeOfArray){
    
    for(int x = 0; x < sizeOfArray; x++){
    
        cout << setw(5) << examMarks[x];
    }
    cout << endl;
    }
    
     void printHisto(int examMarks[], int sizeOfArray){
    system("cls");
    
    for( int x = 0; x < 6; x++){
    cout << setw(5) << "*" << endl;
    }
    }
    
    int main() 
    {
    int examMarks[5];
    
    readExamMarks(examMarks, 5);
    printHisto(examMarks, 5);
    printExamMarks(examMarks,5);
    
    
    system("PAUSE");
    }
    

2 个答案:

答案 0 :(得分:0)

  

如何编辑我的代码以仅允许readExamResults存储代码   在0 -100

范围内

我猜你的意思是readExamMarks而不是readExamResults。如果是这样,您只需要添加一个if语句来检查输入值是否在[0..100]范围内。我还将循环语句for更改为while,因为您只想在输入有效数字时增加idx

void readExamMarks(int examMarks[], int sizeOfArray)
{
     cout << "Please enter a set of exam marks to see a histogram for:" << endl;
     int x = 0;
     int idx = 0;
     while(idx < sizeOfarray)
          cin >> x;
          if((x >=0) && (x <= 100)){
               examMarks[idx] = x;
               idx++;
          }
          else
               cout << "ERROR: Value must be in range [0...100], please enter a valid value\n"; 
     }
}

答案 1 :(得分:0)

基本上,您创建一个新数组,每个十年都有一个条目。然后迭代考试成绩并增加直方图中的相应十年:

vector<int> calculateHistogram(vector<int> grades) 
{
    vector<int> histogram(10, 0);
    for (int i=0; i<grades.size(); i++) {
        int decade = grades[i]/10;
        histogram[decade] += 1;
    }
    return histogram;
}