• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

How does the % operator work?

 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Could anyone explain how you use % as a logical operator?
Maybe another example is better but this was the one I found in the course I'm taking on Java..
 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
% gets you the remainder of a division. In this case, a number is odd when the remainder is not zero when you divide it by two.
 
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
number % 2 == 0 translates to : is the number an even number ? (hope you realize, if after dividing a number remainder is zero, it is even number)
but the *full* code snippet looks strange to me. Value of odd will be false when number is even, and vice versa. wonder what the code does, though.
 
Marshal
Posts: 80295
434
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There is a neater way to do itBecause the % operator has a higher precedence than !=, you don't need any (round brackets).

There is a quicker way to do itNote that the & operator will give much faster performance than % because it is simply comparing bits, not dividing, but the (round brackets) are needed here. I shall leave the reader to work out how it works, and also to work out which range of operands it will work for.
 
Campbell Ritchie
Marshal
Posts: 80295
434
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
And welcome to the Ranch , Wouter Hermans.
 
I have always wanted to have a neighbor just like you - Fred Rogers. Tiny ad:
New web page for Paul's Rocket Mass Heaters movies
https://coderanch.com/t/785239/web-page-Paul-Rocket-Mass
reply
    Bookmark Topic Watch Topic
  • New Topic