C ++(负验证不起作用 [英] C++ (negative verification is not working
问题描述
测试cin的非数字,非零和非负值并进入循环。无法看到为什么对值<= 0的测试不起作用。它应该输出:
Testing cin for non numeric, non zero,and non negative values and entering loop. Cannot see why the test for values <=0 portion is not working. it should output:
cout << "Invalid value input\n";
在此先感谢您发现可能是一个愚蠢的错误。
Thanks in advance for catching what is probably a silly error.
#include <iostream>
using namespace std;
int main()
{
unsigned int integer;
cout<< "Enter a non negative number greater than 0: ";
cin>> integer;
do
{
while(!cin || integer <= 0)//validation condition
{
cout << "Invalid value input\n";
cin.clear();
cin.ignore(200, '\n');
cout<< "Enter a non negative number greater than 0: ";
cin>> integer;
}
cout<< "Enter a non negative number greater than 0: ";
cin>> integer;
} while(integer !=1);
return 0;
}
推荐答案
由于 unsigned int integer;
。
将此值更改为int integer可检查否定验证。
无符号int值的范围是0到4,294,967,295(4字节)
因此,无符号-1表示4,294,967,295,因为-1位表示形式是111〜11( 32个)
您可以检查 2的补语二进制减法,以及-1如何变成2 ^ 32-1
It's not working because of unsigned int integer;
.
Changing this to int integer to check for negative verification.
Range of the value of an unsigned int is 0 to 4,294,967,295 (4 bytes)
So -1 in unsigned means 4,294,967,295 as -1 bit representation is 111~11 (32 Ones)
You may check 2's Complement for binary bit subtraction and how -1 became 2^32-1
这篇关于C ++(负验证不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!