7 ms·
There are lots of everyday uses (not mathy domains) for % operator. Some examples... Outputting a text report with columns. If there were 5 columns, use the
by jasode 10y ago
There are lots of everyday uses (not mathy domains) for % operator.
Some examples...
Outputting a text report with columns. If there were 5 columns, use the "col=i%5" to put it in the correct column as "i" is incremented.
date/time calcs such as...
x%7 is often used for day-of-the-week algorithms
x%3600 and x%60 is often used for converting raw seconds (e.g. convert 86400 seconds per day into hh:mm:ss)
(If programmer doesn't know modulus "x%7", he might hardcode a big switch statement with 7 cases -- which will work, but it's not as elegant.)
round-robin in discrete integer values --> use % modulus
round-robin in continuous values --> use trig sin(), cos()
- busterarm 10y agoWorking with dates and time has so many edge cases and gotchas that I think it's irresponsible not to use a library for working with them. Any good Date(Time) library should abstract this away from you. Say Hello to Leap Seconds for me.
- jasode 10y agoIt's common to have a value called "total_elapsed_seconds" which comes from job logs, traces, etc and "leap seconds" wouldn't be relevant. You just want to "pretty print" it into hhh:mm:ss and %mod is the easiest way to calc that. I've used % for various unrelated tasks for more than 20 years. Another example... in languages that didn't have bit shifting like C/C++, I used % to convert bytes to a hex string (e.g. x%16).
- busterarm 10y agoI guess what I'm saying is... is calculating it easier than going: x = Time ( now ) ... total_elapsed_time = Time ( now ) - x print strftime ( total_elapsed_time ) I've actually used your hex example once before!