c++ - 我的函数跳过了 C++ 中的循环参数
问题描述
我的 GetMark() 函数,它应该检查正确的范围,然后返回值,如果在我添加 SearchMark() 之前,当给定的参数超出接受的范围时,给定的数组会陷入无限循环函数它工作正常并且只循环直到用户最终输入给定范围(0 - 100)内的值,但现在在给出第一个超出范围的值后,无论输入什么,它都会循环,我将感谢任何建议。完整代码:
int GetMark(int ModuleIndex) //user input function
{
bool help;
if (ModuleIndex < 0 || ModuleIndex >100)
{
help = false;
while (help != true)
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "hey, that's a invalid value, try again!" << endl;
GetMark(ModuleIndex);
if ((ModuleIndex > 0) &&( ModuleIndex < 101))
{
help = true;
}
}
}
return ModuleIndex;
}
int SearchMark(int A[], int a) //search grades array for numbers of specific grades
{
int i = 0;
int ii = 0;
while (i < 12)
{
if (A[i] == a)
ii++;
i++;
}
cout << "Mark " << a << " was found: " << ii << " times" << endl;
return 0;
}
int main()
{
int marks[12];
int i = 0;
int sum = 0;
int grades[12];
while (i < 12)
{
cout << "enter mark (0 - 100): " << endl;
cin >> marks[i];
GetMark(marks[i]);
sum = sum + marks[i];
if (marks[i] > 69)
{
grades[i] = 1;
}
else if (marks[i] > 59 && marks[i] < 70)
{
grades[i] = 2;
}
else if (marks[i] > 49 && marks[i] < 60)
{
grades[i] = 22;
}
else if (marks[i] > 39 && marks[i < 50])
{
grades[i] = 3;
}
else if (marks[i] < 35)
{
grades[i] = 4;
}
i++;
}
sum = sum / 12;
cout << "your average is: " << sum << endl;
if (sum > 69)
{
cout << "You passed with 1st!" << endl;
}
else if ((sum > 59) && (sum < 70))
{
cout << "You passed with 2i!" << endl;
}
else if ((sum > 49) && (sum < 60))
{
cout << "You passed with 2ii!" << endl;
}
else if ((sum > 39) && (sum < 50))
{
cout << "You passed with 3rd!" << endl;
}
else if (sum < 40)
{
cout << "Your average is too low! You failed." << endl;
}
i = 0;
while (i < 12)
{
if (marks[i] < 35)
{
cout << "Referred in module " << i + 1 << " mark too low." << endl;
}
i++;
}
SearchMark(grades, 1);
SearchMark(grades, 2);
SearchMark(grades, 22);
SearchMark(grades, 3);
SearchMark(grades, 4);
return 0;
}`
解决方案
该功能的功能过于复杂。只需在值错误时循环,并提示输入新值:
int GetMark(int ModuleIndex) {
while (ModuleIndex < 0 || ModuleIndex > 100) {
std::cout << "Invalid value.\n"
std::cin >> ModuleIndex;
}
return ModuleIndex;
}
递归在理论分析中非常方便,但在实践中它几乎总是一个错误。
推荐阅读
- mysql - 如何将参数作为种子值添加到 sequelize.rand() 以获得类似于 ORDER BY RAND(seed_value) 的效果
- javascript - 无法在 next.js 中导入 coreui/react 组件。出错
- python - 如何在 pymongo 中使用 upsert?
- python - python ipyvuetify 关闭浮动对话框(ipywidgets)
- r - 将 *.Rmd 文件渲染为 html - 缺少一些 YAML 标头条目
- sql - 在动态 SQL 中调用自定义聚合函数时的转换问题
- javascript - 检查是否注册了自定义 URI
- sql - Oracle 中的 FORCE EDITIONABLE 视图
- c# - 使用 XmlAnyElementAttribute 反序列化对象不起作用
- python - Numpy按数组切片?