constexprintscores[]{84,92,76,81,56};constexprintnumStudents{static_cast<int>(std::size(scores))};// const int numStudents{ sizeof(scores) / sizeof(scores[0]) }; // use this instead if not C++17 capableinttotalScore{0};// use a loop to calculate totalScorefor(intstudent{0};student<numStudents;++student)// 这里 student{0} 其实就是 i=0totalScore+=scores[student];autoaverageScore{static_cast<double>(totalScore)/numStudents};
#include<iostream>#include<iterator> // for std::sizeintmain(){// scores are 0 (worst) to 100 (best)constexprintscores[]{84,92,76,81,56};constexprintnumStudents{static_cast<int>(std::size(scores))};intmaxScore{0};// keep track of our largest scorefor(intstudent{0};student<numStudents;++student){if(scores[student]>maxScore){maxScore=scores[student];}}std::cout<<"The best score was "<<maxScore<<'\n';return0;}
#include<iostream>#include<iterator>intmain(){constexprintscores[]{84,92,76,81,56};constexprintnumStudents{static_cast<int>(std::size(scores))};intmaxScore{0};// keep track of our largest scorefor(intstudent{0};student<=numStudents;++student){if(scores[student]>maxScore){maxScore=scores[student];}}std::cout<<"The best score was "<<maxScore<<'\n';return0;}