Re: Mod (%) function in C/Objective-C?
Re: Mod (%) function in C/Objective-C?
- Subject: Re: Mod (%) function in C/Objective-C?
- From: Dave <email@hidden>
- Date: Mon, 11 Aug 2014 22:03:49 +0100
On 10 Aug 2014, at 17:04, Scott Ribe <email@hidden> wrote:
> On Aug 10, 2014, at 9:16 AM, Keary Suska <email@hidden> wrote:
>
>> I don't think so, although I would expect a C lib somewhere to address it.
>
> I think the standard C libs only have floating-point versions of mod functions. (That does seem like an odd omission.)
>
> This would at least be a tiny bit better if people would learn to quit incorrectly referring to % as mod, but I guess that ship has sailed (all the way off the edge of the earth, actually)…
Actually I think it’s circumnavigated it a few times!
That’s why I made the mistake in the first place, I was think of % as being a true mod function, not a remainder. In Ruby for instance it works as you’d expect a mod function to work and it uses % too, not sure about Java?
From doing a bit of digging:
Based on the C99 Specification: a = (a / b) * b + a % b
We can write a function to calculate (a % b) = a - (a / b) * b!
int remainder(int a, int b)
{
return a - (a / b) * b;
}
For modulo operation, we can have the following function:
int mod(int a, int b)
{
int r = a % b;
return r < 0 ? r + b : r;
}
My conclusion is (a % b) in C is a remainder operator and NOT modulo operator.
All the Best
Dave
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden