有没有办法使用 break 语句来解决
Is there a way to work around using a break statement?
我有一个有效的二进制搜索函数,它要求用户输入一个名字,它将在学生数组结构中搜索它并显示该学生的相应平均 GPA。除非用户输入句点,否则它将不断循环供用户输入要搜索的名称。
我遇到的问题是我正在使用的break
语句。我需要遵循的此函数的要求不允许我使用 break
语句。
但是,如果我删除 break
语句,我的二进制搜索将无限打印输出语句,并且无法再正常工作。
有没有办法让我解决这个问题而不使用 break
语句?我有一种感觉,我可以使用几个if
语句而不是break
语句。
void binarySearch(Student* ptr, int MAXSIZE)
{
string target;
string period = ".";
int first = 0,
last = MAXSIZE - 1,
mid;
do
{
cout << "Enter student name (Enter . to stop): ";
cin >> target;
while (first <= last)
{
mid = (first + last) / 2;
if (ptr[mid].name.compare(target) == 0)
{
cout << "Student " << target << " :gpa " << ptr[mid].avg << endl;
first = 0;
last = MAXSIZE - 1;
break; // I am stuck on making the binary search work without using this break statement
}
else if (ptr[mid].name.compare(target) < 0)
last = mid - 1;
else
first = mid + 1;
}
if (first > last && target.compare(period) != 0)
{
cout << "This student was not found. Enter another name" << endl;
first = 0;
last = MAXSIZE - 1;
}
} while (target.compare(period) != 0);
}
在你的
循环中引入一个bool
!
bool nameFound = false;
while (first <= last && !nameFound)
{
mid = (first + last) / 2;
if (ptr[mid].name.compare(target) == 0)
{
cout << "Student " << target << " :gpa " << ptr[mid].avg << endl;
first = 0;
last = MAXSIZE - 1;
nameFound= true;
}
...
}
将要从中break
的while
循环放在其自己的独立函数中。
现在,return;
将具有与break;
相同的效果。
这是我认为的解决方法
do{
int ctr = 0;
while (first <= 0 && ctr ==0)
{
if (ptr[mid].name.compare(target) == 0)
{
cout << "Student " << target << " :gpa " << ptr[mid].avg << endl;
first = 0;
last = MAXSIZE - 1;
ctr = 1 ;
}
}
}
<</div>
div class="answers"> 只是一个风格评论(因为实际答案已经发布):如果您在需要之前设置必要的工作变量,而不是依靠各种退出情况来重置它们以供将来迭代,则更可靠。即:
....
cin >> target;
// Define and initialize right before they are needed.
int first = 0;
int last = MAXSIZE - 1;
while (first <= last) {
int mid = (first + last) / 2; // Not needed outside the loop
一个简单的
解决方案是将break
替换为goto
,并在while
后引入一个标签,例如:
do {
// ...
goto pointless;
// ...
} while (bla);
pointless: ;
注意:这比在各方面使用break;
更糟糕,除了遵守您声明的不使用break
的要求。
相关文章:
- 运行同一解决方案的另一个项目的项目
- Project Euler问题4的错误解决方案
- Ardunio UNO解决了多个重叠的定时器循环
- 我的简单if-else语句是如何无法访问的代码
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- 为什么是0;C++中的有效语句
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- Insert函数不适用于2 if语句C++
- 两个文件使用彼此的功能-如何解决
- 计算每个节点的树高,帮助我解释这个代码解决方案
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 如何解决"invalid conversion from 'char' to 'const char*'"
- 是否可以使用if constexpr删除控制流语句
- Arduino 用于语句错误。令牌之前的预期')' ';'。如何解决这个问题?
- R6010 执行后出错.if 语句在 for 循环中.[作业][中止已解决,发现新问题]
- 如果语句在满足条件C++仍无法解决
- 有没有办法使用 break 语句来解决