Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/162.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 给出了向量的误差_C++_Vector - Fatal编程技术网

C++ 给出了向量的误差

C++ 给出了向量的误差,c++,vector,C++,Vector,我试图写一个程序,但我的编译器在第一个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;

我试图写一个程序,但我的编译器在第一个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;
}
#包括
#包括
使用名称空间std;
int main()
{
/*A=4
B=3
C=2
D=1
F=0*/
双gpa=0;
煤焦品位;
国际贸易额;
分额;
cin.ignore();
病媒等级;

对于(int i=1;i ),您有索引问题。C++中的数组是零索引的。在第一个循环中,很明显,您希望在1开始向用户呈现网格计数。而万无一失的方法是将每个循环设为…

for(int i = 0; i < elements; i++) {}
for(inti=0;i
然后在初始循环中,使用以下命令获得所需的行为

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

cout不要在main上执行递归!你在做什么,你首先接受了不正确的输入,然后创建了数据的整个副本,从一开始就可以再次执行所有这些操作。退出main后,你将返回相同的for()循环

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

实际上,你的分数计算器可能会更短。如果你使用for(),你可以使用迭代器,也可以使用
#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 ... 
或使用()的范围:

将检查是否正确输入移动到进行输入的循环中,使用

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

if((c>='A'))&&(c
int i=0;i解决此类问题的正确工具是您的调试器。在询问堆栈溢出问题之前,您应该逐行检查代码。有关更多帮助,请阅读。您的问题至少应该包括一个重现您的问题的示例,以及您在调试器中所做的观察。
for (char c : grades)
    gpa += rates.find(c); 
if((c>='A')&&(c<='F'))