Re: "make positive" function
Re: "make positive" function
- Subject: Re: "make positive" function
- From: Cem Karan <email@hidden>
- Date: Mon, 11 Sep 2006 16:23:05 -0400
Message: 17
Date: Mon, 11 Sep 2006 19:28:29 +0100
From: Mike Abdullah <email@hidden>
Subject: "make positive" function
To: email@hidden
Message-ID: <email@hidden>
Content-Type: text/plain; charset=US-ASCII; delsp=yes; format=flowed
I'm not a C expert, so apologies for this one:
Basically, I want to take a double and get its closest positive
integer. I haven't been able to find anything that does what I want
(I have a feeling it might be a modulus?).
Anyway, it seems to me I have 3 options:
1. There is an existing, simple function in C - if so can someone
tell me what it is ? :)
2. Do the incredibly clunky, square variable, find square root
3. Write my own function.
Mike.
Look in the second function, it contains what you want. The rest is
so that you can play with the code and see what rounding methods
there are, etc. If you are going to be coding a lot in C, I suggest
(eventually!) getting the C standard, ISO/IEC 9899:1999, or at least
a good book that covers it. Also, this is probably better discussed
on the darwin-dev list.
#include <fenv.h>
#pragma STDC FENV_ACCESS
#include <math.h>
#include <stdio.h>
static void printRoundingMode(void)
{
printf("Rounding mode = ");
switch(fegetround())
{
case FE_TONEAREST:
printf("FE_TONEAREST\n");
break;
case FE_TOWARDZERO:
printf("FE_TOWARDZERO\n");
break;
case FE_UPWARD:
printf("FE_UPWARD\n");
break;
case FE_DOWNWARD:
printf("FE_DOWNWARD\n");
break;
}
}
static void printRoundedNumber(double number)
{
double x;
int y;
/*************************************************************
The interesting part for you is below
*************************************************************/
x = fabs(number);
y = nearbyint(x);
printf("Original number = %F ", number);
printf("absolute value = %F ", x);
printf("int value = %d\n", y);
}
int main(int argc, char *argv[])
{
double x;
int y;
fesetround(FE_TONEAREST);
printRoundingMode();
printRoundedNumber(-12.35);
printRoundedNumber(-14.55);
fesetround(FE_UPWARD);
printRoundingMode();
printRoundedNumber(-12.35);
printRoundedNumber(-14.55);
return 0;
}
Thanks,
Cem Karan
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden