简体   繁体   中英

how to get 2 false Boolean and return true as result

In math, we have -1 * -1 = 1 . When 2 negatives multiplies together, we get a positive.

However in C# bool , I am not able to find a way to do so.

int i = -1
int j = -1

bool bi = i>0
bool bj = j>0

Console.writeLine (bi) 
Console.writeLine (bj)
Console.writeLine (bi && bj)

result:

false

false

false

obviously, the && is the not the right operator. Which operator allows me to have 2 Boolean when both are false, returning true

ie Console.Writeline (false false) result true

The closest to your logic is using negated XOR:

! (bi ^ bj);

This way you'd get something like:

1 * 1 = 1
-1 * 1 = -1
1 * -1 = -1

Also you could use simple comparison operator == :

bi == bj;

Which operator allows me to have 2 Boolean when both are false, returning true

If you want to check two values are equal (eg both are true or both are false ) then == (the equality operator ) is your best bet.

var bob = true == true;
var bob2 = false == false;

Both bob and bob2 will be true .

This is perfect for your problem since you want to know if both numbers are negative or both numbers are positive (since in either of those scenarios, multiplying them will result in a positive number).

Console.Writeline(bi == false && bj == false) 或简称 (!bi && !bj)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM