While循环表达式

While loops expression

本文关键字:表达式 循环 While      更新时间:2023-10-16

我正试图编写一个程序,要求用户输入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(..)