开发者

Better ways to find if both variables are true or both are false

I have two variables which can be either true or false. I get these by doing query on database for presence or absence of certain product ids.

Now I need to set another var开发者_C百科iable which will be true or false. it will be true value when both the variables are true or both are false. It will be false value of one is true and other is false.

at present I take care of it using if statement

if ( v1 == true && v2 == true )
 result = true;
else if ( v1==false && v2 == false )
 result = true;
else if ( v1 == true && v2 == false )
 result = false;
else if ( v1==false && v2 == true )
 result = false;

Is there exists a better way of doing this ?


I may be missing something very fundamental, but I'll give it a go:

result = ( v1 == v2 );


You can use the logical XOR operator and logical NOT operator as:

result = !(v1^v2);


This sort of problem, given a truth table, minimize the logic required to reproduce the truth values, is often nicely treated, with Karnaugh Maps

Your truth table here looks like:

 v1 v2  f(v1, v2)
  t  t     t
  t  f     f
  f  t     f
  f  f     t

And actually, as others have noted, given that truth table, a basic familiarity with logic should right away yield the function !xor

However, if you take the truth table and draw it as a Karnaugh Map, it looks like:


        v2
       f   t 
     ---------
 v  f| t | f |
 1  t| f | t |
     ---------

And the function looks like: !v1!v2 || v1v2 which if you look at 2 variable karnaugh map examples again can be seen to simplify to ! xor

Admittedly, 2 variable karnaugh maps are probably best treated with the ordinary logical operations by well, familiarity and memorization. But when expanding beyond 2 variables, Karnaugh maps are very illuminating -- you should look into them.

  • http://www.facstaff.bucknell.edu/mastascu/elessonshtml/Logic/Logic3.html
  • http://www.allaboutcircuits.com/vol_4/chpt_8/5.html
  • http://k-map.sourceforge.net/


Use the XOR operator (^):

boolean result = !(v1 ^ v2)


The simple way is,if the two variables are equal then it should be true and if any one is false it is false. check this one.

if(v1 == v2)
    return true;
else 
    return false;


if(v1 == v2) 
return true; 
else 
return false;


Why not just compare the two?

if(v1 == v2) result = true;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜