Solved

Casting

Posted on 1998-09-23
5
345 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

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

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…
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and inf…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.

821 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