有没有办法使用 break 语句来解决

Is there a way to work around using a break statement?

本文关键字:语句 解决 break 有没有      更新时间:2023-10-16

我有一个有效的二进制搜索函数,它要求用户输入一个名字,它将在学生数组结构中搜索它并显示该学生的相应平均 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;
    }
    ...
}

将要从中breakwhile循环放在其自己的独立函数中。

现在,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的要求。