Casting

Hi,

I have an array of float data type of which I tried to change them to round numbers by casting them to unsigned char data type. But for data such as 3.99, the result of the casting is 3. What can I do so that all the data will be rounded to their nearest values?

Rgds,
MY
misumiAsked:
Who is Participating?
 
rbrConnect With a Mentor Commented:
use floor and ceil.

double x=3.99;
char c;

c=(char)ceil(x);

0
 
ozoCommented:
It won't be the nearest value if you have

double x=3.01;
char c;

c=(char)ceil(x);
0
 
misumiAuthor Commented:


So, what should I do? Must I use both ceil and floor together?
0
 
ozoCommented:
You might consider
c=(char)ceil(x-0.5);
0
 
raybCommented:
Or a variation on ozo's last response:
int n= (int)(your_array_of_floats[index] + 0.5);
0
All Courses

From novice to tech pro — start learning today.