[英]Need help understanding what's going on in my while loop
My program executes just fine, but I have questions about how my while
loop is set up. 我的程序执行得很好,但我对如何设置
while
循环有疑问。
I know the Boolean values for true and false are 1 and 0, respectively, but I'm not understanding why my output displays the even and odd numbers backwards (to my understanding, it's backwards). 我知道true和false的布尔值分别是1和0,但是我不明白为什么我的输出向后显示偶数和奇数(据我所知,它是向后)。 Simply put, I don't understand why
if ( number % 2 == 0 )
would display that a number is even and when I change it to 1, it displays odd. 简单地说,我不明白为什么
if ( number % 2 == 0 )
显示数字是偶数,当我将其改为1时,它显示为奇数。 I'm reading this line as, if (even number equals to false). 我正在读这行,如果(偶数等于假)。 I don't know if that's where I'm going wrong.
我不知道那是不是我错了。 What's the correct way to read this line?
阅读这条线的正确方法是什么?
The way I have my code set up now displays the numbers correctly, I'm just not understanding why. 我设置代码的方式现在正确显示数字,我只是不明白为什么。 Can anyone help?
有人可以帮忙吗?
// Program indefinitely displays an even
// or odd number until a negative number
// is entered.
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Please enter a number: ";
cin >> number;
while ( number >= 0 )
{
if ( number % 2 == 0 )
{
cout << number << " is even \n";
cout << "Please enter a number: ";
cin >> number;
}
else
{
cout << number << " is odd \n";
cout << "Please enter a number: ";
cin >> number;
}
}
cout << "Thank you. \n";
return 0;
}
number % 2
is 0
if number
divides 2
(ie is even ), 1
if number
is positive and does not divide 2
(ie is odd ), and -1
if number
is negative and does not divide 2
(ie is odd ). number % 2
是0
,如果number
除以2
(即是偶数 ), 1
,如果number
是正的并且不划分2
(即为奇数 ),和-1
如果number
是负的并且不划分2
(即是奇数 )。 (The last point must be the case from C++11 onwards). (最后一点必须是从C ++ 11开始的情况)。
So, since 0 == 0
is true
, number % 2 == 0
is true
if, and only if, number
is even . 因此,由于
0 == 0
为true
,如果且仅当number
为偶数时 , number % 2 == 0
为true
。
So you've written if ( number % 2 == 0 )
to trap all even cases, and the else
traps the odd cases. 所以你写了
if ( number % 2 == 0 )
来捕获所有偶数情况,而else
陷入奇怪的情况。
Testing if ( number % 2 == 1 )
is only a test for positive oddness, but older C++ standards allow this to be true
for negative number
. 测试
if ( number % 2 == 1 )
仅适用于正奇怪的测试,但旧C ++标准允许这是true
阴性number
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.