为矢量给出错误
Error Given For 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;
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;
}
您有索引问题。在C++数组的索引为零。在第一个循环中,很明显您希望从 1 开始向用户显示炉排计数。相反,万无一失的方法是将每个循环表述为 。.
for(int i = 0; i < elements; i++) {}
然后在初始循环中使用以下方法获得所需的行为。
cout << "What is your " << i+1 << " grade? ...
发生越界错误是因为grades.at(grades.size())
在第二个循环中超过了数组的末尾,由于循环遍历grades.size()+1
元素,因此将命中该数组。
不要在 main 上做递归!你在做什么,你首先接受了不正确的输入,然后你创建了数据的整个副本来从头开始做所有这些事情。退出 main 后,您将返回到相同的 for(( 循环。
你在 if 中出错,使用 = 而不是 ==。
实际上你的成绩计算器可能会更短。 如果你使用 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 ...
或使用迭代器:
for(auto it = grades.begin(); it != grades.end(); it++)
gpa += rates.find(*it);
或使用范围 for((:
for (char c : grades)
gpa += rates.find(c);
将检查是否正确输入移动到您 DO 输入的循环中,使用
if((c>='A')&&(c<='F'))
或类似的东西。这将是程序的理智行为
相关文章:
- 分段错误当我试图运行程序时出错
- .h 和.cpp文件分离时出错,但仅使用 .h 文件时没有错误.我做错了什么?
- 创建 OpenCV 非自由版本 v4.3 时出错,可折叠.cpp错误 C2039、2605
- 制作时出错,C++"db.c:2127:错误:在"||"标记之前应使用";"
- C++语法错误,编译器不会警告或 int v = func(&v) 出错;
- 在VS2015中访问类成员时运行时错误,但在Linux上未访问时出错
- 如何更改路径以修复错误"./main:加载共享库 libmkl_core.so 时出错?
- 为什么在定义类之前声明类的对象会在友元类中给出错误,而在友元函数中不会出错
- 安装 mply 库时出错.致命错误:gsl/gsl_sf.h:没有这样的文件或目录
- Rcpp/C++/R:比较日期时间矢量与日期时间时出错(错误:"运算符>"的不明确重载)
- 编译特征程序时出错:错误:'seq'不是'Eigen'的成员
- 可能的 GCC 链接器错误会导致将弱符号和局部符号链接在一起时出错
- 非标准语法;使用 '&' 创建指向成员的指针错误,将成员函数分配给向量时出错
- 运算符重载时出错(错误:"运算符<<不匹配(操作数类型为"std::basic_ostream<char>"和"const char [2]")
- 编译类 C++ 中的线程时出错(错误 xthread)
- 加载GLEW库时出错(错误LNK2001)
- 通过函数指针调用函数时出错(错误C2064)
- 编译core.obj时出错:错误LNK2001:未解析的外部符号_harmony_core_init
- 链接c++静态库与android ndk时出错(错误:无法识别文件格式)
- 使用GCC编译游戏时出错.(错误:将"Screen"的含义从"class Screen&q