【发布时间】:2019-08-04 13:56:30
【问题描述】:
我的 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;
}`
【问题讨论】:
-
除了使用递归而不是简单迭代的问题之外,我注意到 ModuleIndex 的值在调用 GetMark 后永远不会改变。因此,如果它超出范围,您只需使用相同的超出范围值一次又一次地无限递归。
-
@L.ScottJohnson 它确实发生了变化,如果超出范围,它每次都会提示用户输入新的输入值
-
它提示,是的。但它不会读取用户对提示的响应。
-
代码可以通过彻底改变来优化。为什么这样,例如 `cin >> 标记[i]; GetMark(marks[i])`?
-
如果被调用,
GetMark()不会读取任何值,并使用传递给它的值递归调用自身。这导致无限递归。递归调用GetMark()之后的代码永远不会到达。
标签: c++ function loops infinite-loop