在 WHILE 循环中使用 if 和 else

use of if and else in a while loop

本文关键字:if else WHILE 循环      更新时间:2023-10-16

所有代码都工作正常,但是当其他程序实现时关闭,我希望代码应该再次请求输入,需要帮助!

 #include<iostream>
using namespace std;
int main()
{
  int total;    // this is the number which is the multiple of 10
  cout<<"Enter a number = ";
  cin>>total;
  while(total!=-1)  
  {
    if (total % 10 == 0) 
    {        
      total=total-10;
      total=total/5;
      cout<<"total= "<< total<<endl;
      cout<<"1st number= "<<total<<endl;
      cout<<"2nd number= "<<total+1<<endl;
      cout<<"3rd number= "<<total+2<<endl;
      cout<<"4th number= "<<total+3<<endl;
      cout<<"5th number= "<<total+4<<endl;
      break;    
    }
    else 
    {
      cout<<"re-enter the number"<<endl;    
      break;
    }
    return 0;
  }
}

从其他原因中删除break;并添加cin>>total;

else 
{
    cout<<"re-enter the number"<<endl;  
    cin>>total;
}

只需从else子句中删除break;语句即可。 break;会导致最近的封闭环路(或开关)退出,在您的情况下是while()环路。

此外,在这种情况下,您将不得不再次请求输入,因此请在else分支中再次阅读total

通常,break;会导致程序控制退出包含break的最内层循环。因此,在您的情况下,它会导致while完成。

我认为您将if块与switch的语法混淆了.在 switch 块中,break 确实是必要的,以避免单个 case 语句的默认跟进行为。

您可能还需要重新定位return 0;语句:这将导致程序退出,0返回到命令外壳。

与其使用break,不如在这里使用 continue,这将进入循环的顶部。循环中也有一个 return 语句,因此continue将跳过此语句。要么,要么你也必须删除return,你也需要返回main