Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

 
 
Thread Tools Display Modes
Prev Previous Post in Thread   Next Post in Thread Next
Old Feb 17th, 2005, 4:43 PM   #1
Jared
Newbie
 
Join Date: Feb 2005
Posts: 2
Rep Power: 0 Jared is on a distinguished road
Problem converting double to int

First of all, this is standard C.

I have a statement in my code like this:
int x = log(8)/log(2)

After much confusion I found that x was assigned 2. This is not what I want though. I know that log(8)/log(2) equals 3.000000... in double and I want it to convert that to the integer 3 and save it into x. For some reason it will not do this though. I have tested by just putting
double x = 3;
int a = x;
printf("a: %d", a);
and it prints out a 3 so I do know that it works in that case. When I use the log() function for some reason it floors the 3.000000... and makes it a 2. Is there any way to fix this so int x equals 3?
I also tried this:
double x = log(8)/log(2);
int a = ceil(x);
printf("a: %d", a);
which gave me the right number 3. I don't know how the ceiling of 3.000000... would be 3 and the floor of 3.000000... would be 2.

The actual use of the statement in my code is in a function:
arrayInsert(int n, int *array){
int a = log(n)/log(2);
int b = a - 1;
int j = n + pow(2, b);
.
.
.
}
a is assigned the right value everytime except when n = 8. log(2)/log(2) works, log(4)/log(2) works, log(16)/log(2) works, but log(8)/log(2) never works. I don't know how one value of it would cause problems. I'm using Visual Studio, could it have a bug in it?
Jared is offline   Reply With Quote
 

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 10:21 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC