ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
The following code is meant to convert an int to a float in C, but its not working!!! I need to use ints because of the mod (%) operation, but i need the results as a float.
{
int tempx;
int tempz;
float fx;
float fz;
/* sizex, sizez and resolution are all predetermined int values
rand initialised using srand(time(NULL));
*/
tempx = ((rand())%(sizex * resolution)) - (sizex * resolution / 2);
tempz = ((rand())%(sizez * resolution)) - (sizez * resolution / 2);
fx = tempx;
fz = tempz;
}
I've tried using:
fx = (float)tempx;
fx = *((float*)&tempx);
But nothing seems to work, i get valid tempx and tempz values, but they go crazy when converted to float.
Ie. tempx = 9865, tempz = 5806, converts to fx = 0, fz = 1086538880
Typecasting an int to a float is surely not what you want. That tells the computer to interpret the bits in the int as a float; those two data types most assuredly do not use the same format. Though, I will say I'm surprised the original "fx = tempx;" didn't work. I could swear I've done something like that before. I'll need to reboot into Linux to double-check.
By the way, how do you know what the values of fx and fz are? Through a debugger, or do you display them with a printf()? If printf(), make sure you're using the right conversion character. If you try to print a floating point as an int, you'll get crazy results.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.