Solved

Casting

Posted on 1998-09-23
5
337 Views
Last Modified: 2010-04-15
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
0
Comment
Question by:misumi
5 Comments
 
LVL 10

Accepted Solution

by:
rbr earned 10 total points
ID: 1253006
use floor and ceil.

double x=3.99;
char c;

c=(char)ceil(x);

0
 
LVL 84

Expert Comment

by:ozo
ID: 1253007
It won't be the nearest value if you have

double x=3.01;
char c;

c=(char)ceil(x);
0
 

Author Comment

by:misumi
ID: 1253008


So, what should I do? Must I use both ceil and floor together?
0
 
LVL 84

Expert Comment

by:ozo
ID: 1253009
You might consider
c=(char)ceil(x-0.5);
0
 
LVL 2

Expert Comment

by:rayb
ID: 1253010
Or a variation on ozo's last response:
int n= (int)(your_array_of_floats[index] + 0.5);
0

Featured Post

Does Powershell have you tied up in knots?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now