《C++ Primer》(第五版)中计算vector对象中的索引这一小节中,举例要求计算各个分数段各有多少个成绩。

代码如下:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main(){
    vector<unsigned> scores(11, 0);
    unsigned grade;
    while (cin >> grade){
        if (grade <= 100)
            ++scores[grade/10];
    }
    return 0;
}

当需要输出时,自己试着敲入:

cout << scores << endl;

发现程序报错:

error: invalid operands to binary expression ('ostream'
      (aka 'basic_ostream<char>') and 'vector<unsigned int>')

发现是类型问题,所以重新定义一下scores类型,使用范围for语句:

for (auto i : scores)
    cout << i << " ";
cout << endl;

改为:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main(){
    vector<unsigned> scores(11, 0);
    unsigned grade;
    while (cin >> grade){
        if (grade <= 100)
            ++scores[grade/10];
    }
    for(auto i : scores)
        cout << i << " ";
    cout << endl;
    return 0;
}

这样就能把各个分数段各有多少个成绩序列打印出来了。

相关文章:

  • 2021-07-21
  • 2021-06-04
  • 2021-04-27
  • 2021-09-01
  • 2022-01-03
  • 2021-06-29
  • 2021-12-04
  • 2022-01-06
猜你喜欢
  • 2021-07-27
  • 2021-07-22
  • 2021-12-05
  • 2021-09-20
  • 2021-10-25
  • 2022-02-27
  • 2021-12-03
相关资源
相似解决方案