Jump to content
  • Advertisement
Sign in to follow this  
XandX2005

Modulus use in c++

This topic is 3488 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm kind of confused on the modulus (%) and what it does and how to use it. I would like to see some examples too. Thanks --Garren

Share this post


Link to post
Share on other sites
Advertisement
Confusing? It gives you the remainder of a division operation. It's not used frequently. Occasionally for mathematical algorithms, occasionally to do something every... x iterations:



for( int i = 0; i < 100; ++i){
std::cout << i;
if( i%5 == 0 ){
std::cout << std::endl;
}
}
// 0
// 12345
// 678910
// 1112131415
// etc.


Sometimes to split a number:



int moneyInCents = 4321;
int cents = moneyInCents % 100; // 21
int dollars = (moneyInCents - (moneyInCents % 100))/100; // 43



Most often its used with ==0 to see if something is exactly divisible, as in the iteration example.

Share this post


Link to post
Share on other sites
Think of it as "remainder." m % n returns the remainder of dividing m by n. e.g., 16 % 3 → 1, 19 % 4 → 3, 2 % 3 → 2

Share this post


Link to post
Share on other sites
its simple. modulo is used when you want to get the REMAINDER of a statement for example 6 % 2 would equal 0 there is no remainder. 5 % 2 would equal 1 as 2 goes into five twice with a remainder of one. so modulus simply returns the remainder pretty easy. pretty straight forward

Share this post


Link to post
Share on other sites
Quote:
Original post by Oluseyi
Think of it as "remainder." m % n returns the remainder of dividing m by n. e.g., 16 % 3 → 1, 19 % 4 → 3, 2 % 3 → 2


Ok, now i get. Thanks a bunch.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!