While循环表达式
While loops expression
我正试图编写一个程序,要求用户输入0到1000000之间的数字,并输出某个数字的出现(用户也输入了)
我已经写了这个程序,我相信它运行得很好,但我有一个问题,那就是如果while表达式不是真的,我想定制某个消息,但我不知道该把它放在哪里。
这是我的程序:
#include <iostream>
using namespace std;
int main()
{
int n,j=0,key;
cout << "Pleaser enter digitsn";
cin >> n;
cout << "please enter key numbern";
cin >> key;
while (n>0 && n<1000000)
{
if(n%10==key)j++;
n= n/10;
}
cout << "The number " << key << " was found " << j << " time(s)" << endl;
return 0;
}
提前感谢!
使用
if(n>0 && n<1000000)
{
while(n)
{
if(n%10==key)
j++;
n= n/10;
}
}
else
cout<<"n is supposed to be between 0 and 1000000";
由于bucle内部没有中断(或者没有其他可以跳转的代码),while结构之后的所有内容都会被执行,因为表达式返回false。
while (n>0 && n<1000000)
{
if(n%10==key)j++;
n= n/10;
}
cout << "While expression not anymore true" << endl;
cout << "The number " << key << " was found " << j << " time(s)" << endl;
return 0;
}
更新
根据评论,您似乎想检查输入的数字是否有效。简单地说,只需在此之前检查一下:
if(not (n>0 and n<1000000)) cout << "Number must be between 0 and 1000000" << endl;
else {
while (n)
{
if(n%10==key)j++;
n= n/10;
}
}
cout << "The number " << key << " was found " << j << " time(s)" << endl;
return 0;
}
在while循环之前编写if语句。
if(!(n>0 && n<1000000))
{
cout << "....";
return -1;
}
while(..)
相关文章:
- C++正则表达式无限循环
- 为什么在 while 循环中返回表达式不起作用
- 如何在 c++ 下使用嵌套循环和正则表达式降低时间复杂度?
- 使用 constexpr 或模板元编程简化较长的展开循环表达式
- 符号和未签名整数表达式之间的比较,以进行循环误差
- 循环赋值的多维数组:表达式必须是可修改的左值
- 射击时从列表中删除外星人 - 找出循环;"表达式:无法递增结束列表迭代器"
- 如何在条件表达式中使用 'cin' 正确退出 while 循环?(C++,CLion)
- 基于范围的正则表达式匹配的 for 循环
- C++ 循环:“;”标记之前的预期主表达式
- 逗号(,)在条件部分中两个表达式之间的for循环中的工作方式
- 计算一个表达式来计算循环
- C++ 循环和布尔表达式
- 为什么我的正则表达式会导致无限循环
- 执行基本的 for 循环并得到错误:")"之前的预期主表达式
- 是否可以将多个关系表达式放入 for 循环的测试条件中
- 为什么不能在 do while 循环的表达式部分内声明一个变量?
- 基于范围的 for 循环是否缓存容器表达式,或每次迭代重新计算它
- C++:布尔表达式导致无限 while 循环
- 从嵌套循环创建数学表达式