2017-05-16 214 views
0

我正在尝试编写一个程序,并且我的编译器在第一个for循环之后得到一个错误。我一直试图修复它很长一段时间,但它不起作用。我的编译器说有一个std :: out_of_range错误。顺便说一句,我在编码中。向量给出的错误

#include <iostream> 
#include <vector> 

using namespace std; 

int main() 
{ 
    /* A = 4 
    B = 3 
    C = 2 
    D = 1 
    F = 0*/ 


    double gpa = 0; 
     char grade; 
    int gradeamount; 

    cout << "Welcome to GPA calculator. This tells you your GPA by inputting your grades. How many grades do you have." << endl; 
    cin >> gradeamount; 
    cin.ignore(); 
    vector<char> grades; 

    for(int i = 1; i <= gradeamount; i++) 
    { 
    cout << "What is your " << i << " grade? In Caps Please." << endl; 
    cin >> grade; 
    cin.ignore(); 
    grades.push_back(grade); 
    } 

    for(int i = 0; i <= (int) grades.size(); i++) 
    { 
    if(grades.at(i) = 'A') 
     gpa += 4; 

    else if(grades.at(i) = 'B') 
     gpa += 3; 

    else if(grades.at(i) = 'C') 
     gpa += 2; 

    else if(grades.at(i) = 'D') 
     gpa += 1; 

    else if(grades.at(i) = 'F') 
     gpa +=0; 

    else 
    { 
     cout << "That is not a grade, if it is try capitalizing it." << endl; 
     int main(); 
    } 
    } 


    gpa /= (double) grades.size(); 

    cout << "Your GPA is: " << gpa << endl; 
} 
+1

'int i = 0;我<=(int)grades.size();'几乎从不正确 - 应该只是**'<** **。将额外的'='移到这里:'if(grades.at(i)='A')',因为这是一个赋值,而不是比较。 –

+1

解决此类问题的正确工具是您的调试器。在*堆栈溢出问题之前,您应该逐行执行您的代码。如需更多帮助,请阅读[如何调试小程序(由Eric Lippert撰写)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,你应该[编辑]你的问题,以包含一个[Minimal,Complete,and Verifiable](http://stackoverflow.com/help/mcve)例子来重现你的问题,以及你在调试器中所做的观察。 –

回答

0

您有索引问题。在C++中,数组是零索引的。在第一个循环中,显然你想要给用户开始1的格子数。相反,万无一失的方法是将每个循环表述为。 。

for(int i = 0; i < elements; i++) {} 

然后在最初的循环中使用以下来获得所需的行为。

cout << "What is your " << i+1 << " grade? ... 

的出界误差的发生是因为grades.at(grades.size())是过去在第二循环中的阵列,其将被击中因为随着grades.size()+1元件循环迭代的结束。

0

不要做递归主!你在做什么,你首先接受了不正确的输入,然后你创建了整个数据副本,从一开始就做了所有这些。在你退出main之后,你会返回到()循环中。

您在ifs中有错误,使用=而不是==。

其实您的成绩计算器可能会更短..如果您使用(),您可以使用迭代器或必须使用< grades.size()。否则,你可以抛弃无论是和你的长期IFS在一起,使用lambda功能:

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

//... skipped code ... 

const std::string rates = "FDCBA"; 
std::for_each(grades.begin(), grades.end(), [&gpa,&rates](const char &c) 
{ 
    gpa += rates.find(c); // determine index 
}); 

//... skipped code ... 

或使用iterator:

for(auto it = grades.begin(); it != grades.end(); it++) 
    gpa += rates.find(*it); 

或使用范围():

for (char c : grades) 
    gpa += rates.find(c); 

举动检查以便正确输入到DO输入的回路中,用

if((c>='A')&&(c<='F')) 

或类似的东西。这将是程序的理智行为