|
-
Oct 27th, 2005, 08:12 PM
#1
Thread Starter
Hyperactive Member
sgn()
Does anyone know the equivalent of the sgn() function found in vb for c
the function that returns -1 for negative numbers 0 for 0 and 1 for positive numbers. It is really useful for me in vb, also, would you caution aginst using it because of performance? every .1 milisecond is important in my program
i am just assuming that c# is the same as c
It's not just Good, It's Good enough!
Spelling Eludes Me
-
Oct 27th, 2005, 08:52 PM
#2
Re: sgn()
You could use
Code:
-(0.0).CompareTo(someNumber)
Doing anything 10000 times a second is likely to have an impact on performance.
-
Oct 28th, 2005, 06:53 AM
#3
Re: sgn()
Probably the most efficient way:
Code:
int Sgn(int val)
{
return val < 0 ? -1 : 1;
}
Although, you should just inline the check into your code, instead of relying on checking the return value of a function (which is a branch in itself). It's not worth a function at all.
-
Oct 28th, 2005, 06:55 AM
#4
Re: sgn()
 Originally Posted by notquitehere188
for c
Do you mean C, or C#? They are not the same, in fact they are very different animals. Although the snippet I provided will work in either language, jmcilhinney's will only work in C#.
There is a C/C++ forum further down the index page which is where you should post C questions.
-
Oct 28th, 2005, 08:13 AM
#5
Re: sgn()
I think you have to change your code to this penagate:
Code:
return val < 0 ? -1 : (val > 0 ? 1 : 0)
I don't think the parentheses are needed but they probably help with clarity anyway.
-
Oct 28th, 2005, 08:25 AM
#6
Re: sgn()
My bad. Forgot about zero 
Here is yet another method.
Code:
return (val & 0xf0000000) > 0 ? -1 : val == 0 ? 0 : 1;
That one will also work in C.
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
|