"io_x" <a@b.c.invalid> ha scritto nel messaggio
news:4da09adc$0$18241$4fafbaef@reader2.news.tin.it...
>
> "Geoff" <geoff@invalid.invalid> ha scritto nel messaggio
> news:vk31q617k5188j3qfsalvqj4hjnl05n57h@4ax.com...
>> On Sat, 9 Apr 2011 07:53:05 -0700 (PDT), "dr.oktopus"
>> <blindwilly@freeonline.zzn.com> wrote:
>>
>>>Ok, today I seems to be a little dumb.
>>>What I have to do is to make mod operator (m % n) work even
>>>if m is a negative number.
>>>
>>>This is what I mean:
>>>
>>>given n = 5
>>>
>>> 7 became 2
>>> 6 .. 1
>>> 5 .. 0
>>> 4 .. 4
>>> 3 .. 3
>>> 2 .. 2
>>> 1 .. 1
>>> 0 .. 0
>>>-1 .. 4
>>>-2 .. 3
>>>-3 .. 2
>>>-4 .. 1
>>>-5 .. 0
>>>-6 .. 4
>>>-7 .. 3
>>>
i get only the 3,2,1,0,1,2,3
for me you search somethin like the routine
unsigned myModAlternative(int m, unsigned n)
don't know if it is right [but it is very like as that]
#include <stdio.h>
unsigned myMod(int m, unsigned n)
{unsigned mm;
// prevent seg fault on error but wrong result
if(n==0) return -1;
if(m>=0) {mm=m; return mm%n;}
mm=-m; mm%=n;
if(mm==n) mm=0;
return mm;
}
unsigned myModAlternative(int m, unsigned n)
{unsigned mm;
// prevent seg fault on error but wrong result
if(n==0) return -1;
if(m>=0) {mm=m; return mm%n;}
mm=-m; mm%=n;
if(mm==0) mm=n;
return n-mm;
}
int main(void)
{int i, m, n;
n=5;
for(i=7; i> -7 ; --i)
printf("%2d%%%d = %u\n", i, n, myMod(i, n));
printf("Alternative\n");
for(i=7; i> -7 ; --i)
printf("%2d%%%d = %u\n", i, n, myModAlternative(i, n));
return 0;
}
7%5 = 2
6%5 = 1
5%5 = 0
4%5 = 4
3%5 = 3
2%5 = 2
1%5 = 1
0%5 = 0
-1%5 = 1
-2%5 = 2
-3%5 = 3
-4%5 = 4
-5%5 = 0
-6%5 = 1
Alternative
7%5 = 2
6%5 = 1
5%5 = 0
4%5 = 4
3%5 = 3
2%5 = 2
1%5 = 1
0%5 = 0
-1%5 = 4
-2%5 = 3
-3%5 = 2
-4%5 = 1
-5%5 = 0
-6%5 = 4