zizi21
asked on
Powers of two
hi,
number = log(input)/log(2);
could anyone pls help me...to get the power of two of the input, i am doing this but i got incorrect answer for 8 ...
number = log(input)/log(2);
could anyone pls help me...to get the power of two of the input, i am doing this but i got incorrect answer for 8 ...
ASKER
let say someone input 8,
i need to give the answer 3...
i need to give the answer 3...
ah so you do logs..
Unfortunately the problem is because the log function returns a double number, and double numbers can't be stored 100 percent accurately.
You will probably get some invalid result because of this.
Try using the "ceil, and floor" functions to help you get the correct answer.
Unfortunately the problem is because the log function returns a double number, and double numbers can't be stored 100 percent accurately.
You will probably get some invalid result because of this.
Try using the "ceil, and floor" functions to help you get the correct answer.
You actually could just just try using sprintf
like this:
double result = <log calculation>;
here is an example of only printing only 1 decimal
printf("%8.1d" result); <-- creates a entire width of 8, and only 1 decimal space.
You can read up on this stuff.
here is a link I found:
http://cermics.enpc.fr/~ts/C/FUNCTIONS/format.html
like this:
double result = <log calculation>;
here is an example of only printing only 1 decimal
printf("%8.1d" result); <-- creates a entire width of 8, and only 1 decimal space.
You can read up on this stuff.
here is a link I found:
http://cermics.enpc.fr/~ts/C/FUNCTIONS/format.html
correction:
printf("%8.1d" result);
--> should be printf("%8.1d", result);
printf("%8.1d" result);
--> should be printf("%8.1d", result);
ASKER
thanks...
ASKER
it works with ceil..can i assume it is correct or do i need to check for floor ??
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
thanks
>> to get the power of two of the input,
If the input will be an integer value, this is relatively easy, since you have binary operators.
If the input will be an integer value, this is relatively easy, since you have binary operators.
I agree; I think I probably should have mentioned using bitwise operators, but I wasn't 100 percent clear on if he would be doing this approach only for powers of 2....
Have a look up on "Binary bitwise operators"
Operators: ">>" and "<<" are quite helpful
Have a look up on "Binary bitwise operators"
Operators: ">>" and "<<" are quite helpful
pow(number, power);