[英]Variable shows while in loop but not out of it
So I'm trying to print the first even number of "n". 因此,我正在尝试打印“ n”的第一个偶数。 Somehow, when I try to print the number it would keep reading numbers on console to infinite, but when I print inside the loop it prints "66666666 etc..".
不知何故,当我尝试打印数字时,它将使控制台上的数字一直读到无穷大,但是当我在循环内打印时,它会打印“ 66666666等”。 This is my code:
这是我的代码:
#include <iostream>
using namespace std;
int main()
{
int n,i,x=1;
cin>>n;
while(n){
while(x){
i=n%10;
if(n%2==0){
x--;
}
n/=10;
}
}
cout<<i;
return 0;
}
The problem is your 2 while loops: 问题是您的2 while循环:
while(n) {
while(x) {
//...
}
}
Once x
goes to 0, you end up in the outer loop. x
变为0后,您将进入外循环。
However, this outer loop doesn't modify n
at all. 但是,此外部循环根本不会修改
n
。 So if n
is ever not 0, it will sit there continually. 因此,如果
n
永远不为0,它将连续坐在那里。
The simplest fix is probably just combine them into a single loop: 最简单的解决方法可能就是将它们组合成一个循环:
while(n && x) {
//...
}
Or, you can just use 1 loop and not use x
at all. 或者,您可以只使用1个循环,而根本不使用
x
。
int main()
{
int n,i;
cin>>n;
while(n){
i=n%10;
if(n%2==0){
break;
}
n/=10;
}
cout<<i;
return 0;
}
That should also work as well. 那也应该工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.