|
-
July 11th, 2024, 12:22 AM
#2
Re: Help needed in conversion
To quote C99
4 The result of the binary * operator is the product of the operands.
5 The result of the / operator is the quotient from the division of the first operand by the
second; the result of the % operator is the remainder. In both operations, if the value of
the second operand is zero, the behavior is undefined.
6 When integers are divided, the result of the / operator is the algebraic quotient with any
fractional part discarded.78) If the quotient a/b is representable, the expression
(a/b)*b + a%b shall equal a.
Note the underlined word.
You're also mixing signed and unsigned arithmetic, which is also poorly defined in C.
> it is coming correctly as 25
Weird, I get different answers.
Code:
$ cat foo.c
#include <stdio.h>
void foo ( ) {
long Xmin = -228725;
unsigned long uiRes = 50;
long iXOffset = Xmin % uiRes;
printf("In foo: iXOffset=%ld\n", iXOffset);
printf("Check: %ld == %ld\n", Xmin, (Xmin/uiRes)*uiRes + Xmin%uiRes );
}
void bar ( ) {
long Xmin = -228725;
int uiRes = 50;
long iXOffset = Xmin % uiRes;
printf("In bar: iXOffset=%ld\n", iXOffset);
printf("Check: %ld == %ld\n", Xmin, (Xmin/uiRes)*uiRes + Xmin%uiRes );
}
int main ( ) {
foo();
bar();
}
$ ./a.out
In foo: iXOffset=41
Check: -228725 == -228725
In bar: iXOffset=-25
Check: -228725 == -228725
Both are correct, because the identity "(a/b)*b + a%b shall equal a." holds.
If you're really looking for modulo, then % is the wrong thing to be using if negative values are involved.
https://stackoverflow.com/questions/...gative-numbers
https://en.wikipedia.org/wiki/Modulo...ming_languages
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|