2014-10-06 64 views
0

我想编写一个程序,要求用户0和1000000之间,输入数字和它输出一定数量的发生(即用户输入的为好)while循环表达

我写的这个程序,我相信它运作良好,但我有一个问题,如果while表达式不是真的,我想知道某个消息,但我不知道该把它放在哪里。

这是我的计划:

#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; 
} 

提前感谢!如果语句之前while循环

+0

你可以只换while循环在''if'条件else'块,所以如果'(N <=0 || n > = 1000000)COUT << “参数无效”; else {while ...}' – EdChum 2014-10-06 11:18:46

+0

如果while条件不成立,你**就会执行一个特定的消息。你的意思是“如果表情不是真的*第一次*”? – TobiMcNamobi 2014-10-06 11:18:47

+0

@TobiMcNamobi是的,他的意思是当用户输入n的值不在范围内(0,1000000) – 2014-10-06 11:26:37

回答

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"; 
0

撰写。

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

     while(..) 
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; 
} 

UPDATE

基础上的评论,似乎要检查,如果输入的号码是否有效。简单地说,只是在一段时间之前,检查一下:

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; 
}