0

我正在尝试编写一个程序,要求用户输入 0 到 1000000 之间的数字,并输出某个数字的出现(用户也输入)

我已经编写了这个程序,并且我相信它运行良好,但是我有一个问题是如果 while 表达式不正确,我想 cout 某个消息但我不知道将它放在哪里。

这是我的程序:

#include <iostream> 
using namespace std;
int main()
{ 
 int n,j=0,key; 
 cout << "Pleaser enter digits\n";
 cin >> n;
 cout << "please enter key number\n";
 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;  
}

提前致谢!

4

3 回答 3

2

利用

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";
于 2014-10-06T11:24:08.903 回答
0

在while循环之前写一个if语句。

     if(!(n>0 && n<1000000))
        {
           cout << "....";
           return -1;
        }

      while(..)
于 2014-10-06T11:25:24.143 回答
0

由于 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;  
}
于 2014-10-06T11:25:43.240 回答