gpt4 book ai didi

c++ - vector 下标超出范围错误 C++

转载 作者:行者123 更新时间:2023-11-28 03:05:01 24 4
gpt4 key购买 nike

#include <iostream>  
#include <vector>
#include <iomanip>
#include <cstdlib>
#include <algorithm>

using namespace std;


void determine_grade (double &, char & );
double calc_average (vector <double> averagevector);
double find_highest (vector <double> highestvector);
double find_lowest (vector <double> lowestvector);




int main ()
{
double average = 0.00;
double highest = 0.00;
double lowest = 0.00;
double input;
char letter;
double score = 0;
vector <double> vecinput(0);

for (int i = 0; i < vecinput.size(); i++)
{
cout << " Enter result " << vecinput[i] << "(or -1 if no more result):";
cin >> input;
vecinput[i] = input;
if (input < 0 || input > 100)
{
cout << " Invalid Input";
}
else(input == -1);
{
break;
}


}

determine_grade(score, letter);

cout << " Summary of the Results:" << endl;
cout << " Result" << vecinput.size()<<
cout << setprecision(2) << fixed << score << "Grade" << letter << "\n";

average = calc_average(vecinput);
cout << " The average of the results =" << setprecision (2) << fixed << average << "\n";


lowest = find_lowest(vecinput);
cout << " The lowest of the results =" << setprecision (2)<< fixed << lowest << "\n";


highest = find_highest(vecinput);
cout << " The highest of the results =" << setprecision (2) << fixed << highest << "\n";


system ("Pause");
return 0;
}



double calc_average(vector <double> averagevector) // This function will find the average off the results.
{
double total = 0.00;
double average = 0.00;
for (int i = 0; i < averagevector.size(); ++i)
{
total += averagevector[i];
}
average = (double) total / averagevector.size();
return average;
}


double find_highest (vector <double> highestvector) // This function will find the higest grade of the results.
{
double max= 0.00;
max = *max_element(highestvector.begin(),highestvector.end());

return max;
}
double find_lowest (vector <double> lowestvector) // This function will find the lowest grade of the results.
{
double min = 0.00;
min = *min_element(lowestvector.begin(),lowestvector.end());

return min;
}


void determine_grade (double &num, char &grade)
{

if (num >= 90 && num <= 100)
grade = 'A';
else if (num >= 70 && num <= 89)
grade = 'B';
else if (num >= 60 && num <= 69 )
grade = 'C';
else if (num >= 50 && num <= 59)
grade = 'P';
else
grade = 'U';



}

我正在尝试编写一个必须显示最高、最低等级的程序。我还必须显示平均值和字母等级。我收到一个 vector 下标超出范围的错误。每当我尝试运行该程序时,都在第 932 行。我不确定我做错了什么。

现在我得到一个错误, vector 迭代器不可微分

最佳答案

i <= vecinput.size()

.size()返回 vector 的大小,它们的索引是从零开始的,所以你要越过 vector 的末尾。

使用 <而不是 <= .

还要学习如何使用调试器,因为您可以使用调试器准确找出错误发生的位置。

关于c++ - vector 下标超出范围错误 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19940361/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com