在 WHILE 循环中使用 if 和 else
use of if and else in a while loop
所有代码都工作正常,但是当其他程序实现时关闭,我希望代码应该再次请求输入,需要帮助!
#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
。
相关文章:
- 我的简单if-else语句是如何无法访问的代码
- 如何删除peer if else分支中的冗长句子
- 我似乎对if/else的基本语句有问题:/
- 使用if-else将数字转换为单词
- 为什么这个案例陈述需要一个"if else"而不仅仅是一个"if"?
- C++ If/Else 语句被跳过
- 如果条件不相关,我应该更喜欢两个 if 语句而不是 if-else 语句吗?
- 如何将 if else 语句重写为 switch 语句
- 在 C++ 中的 if-else if- else 语句期间更改变量
- 为什么我的 if else 语句不起作用并从数组中输出正确的索引?
- 我的 If Else 语句无法在向量 (C++) 中提供最大值
- 具有嵌套 if-else 的循环的时间复杂度
- 为什么无论输入如何,所有 if-else 语句都会打印?
- 简化对两个布尔值的 4 个 if/else 检查
- 如何在C++中创建 if else 循环而不是多个嵌套?
- 为什么切换 if else 语句的顺序会导致错误?
- 如何使用 if else 语句
- if/else 语句输出由于加号或减号而未显示正确的消息
- 如何解释 #if/#else 位域?(VC++菜鸟)
- if-else 语句仅按特定顺序工作,我不知道为什么