c++ if statement issues -


below function i'm trying use decide if player has moved checkers piece left or right. moveto holds decimal 5.2 , movefrom hold square number 6.3 difference -1.1 , assigned movevalue (i'm checking trace statement , assigning correctly).

however when hits ifs it's not coming out equal , runs last if statement, if hard code -1.1 movevalue evaluate correctly. ideas why it's not evaluating correctly big help. have posted output running program under code :

int legalplayermove(float moveto, float movefrom) {      float movevalue=(moveto-movefrom);     cout<<"trace move value"<<movevalue<<endl;       if(movevalue==(-1.1))         cout<<"moved left"<<endl;     if(movevalue==(-0.9))         cout<<"moved right"<<endl;     if(movevalue!=-1.1||movevalue!=-.9)         cout<<"that not legal move, please renter square number wish move to."<<endl;      return 0; } 
  • please enter location of piece want move
  • 6.3
  • now please enter move piece
  • 5.2
  • trace move value-1.1
  • that not legal move, please renter square number wish move to.
  • tress key continue . . .

it's problematic compare float or double variables against exact float or double literal values! using operator== isn't idea in general.

use comparison against minimal difference (aka epsilon) of values instead:

if(std::numeric_limits<float>::epsilon() + movevalue > 1.1) { // ... } 

Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

javascript - Using Windows Media Player as video fallback for video tag -

c# - Unity IoC Lifetime per HttpRequest for UserStore -