LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How can I cast an int to a double (C)? (https://www.linuxquestions.org/questions/programming-9/how-can-i-cast-an-int-to-a-double-c-435814/)

smoothdogg00 04-16-2006 09:49 PM

How can I cast an int to a double (C)?
 
How can I cast an int, stored in a variable, to a double?

I am trying to do this:
Code:

double d;
d = (double)strlen(str) \ (double)cols

Its obviously not correct, but that is how I would do it in java. Can anyone help?

Dark_Helmet 04-16-2006 10:32 PM

First, why do you say it's not working? Is it a compile error? What's the compiler's error message? Is it a runtime error? How do you know it's handling it incorrectly? Are you displaying the value after the operation and it's not what you expect?

Need more clarity on what the problem is.

What you've given is not actually doing division. You use a backslash ( \ ) as opposed to a forward slash ( / ) in the statement. A forward slash is used for division. A backslash is used to escape a character.

Second, what you have should cast the variable correctly. If not, I would suggest multiplying the return values by 1.0. Such as this:
Code:

d = (1.0 * strlen(str)) / (1.0 * cols);
Technically, you only need to multiply one operand by 1.0, but it doesn't hurt to do both.

Regardless, the typecasting you used originally should work.

95se 04-16-2006 10:53 PM

Casting an int w/ (double) will do just fine. So, if i were an int, then (double)i would cast i to a double. No need to worry.

smoothdogg00 04-16-2006 11:37 PM

*Edit*
Nevermind this post, I got it figured out, thank you all.


All times are GMT -5. The time now is 01:03 AM.