开发者

C, logs, binary, and the number four. they don't mix

开发者 https://www.devze.com 2023-02-08 05:57 出处:网络
#include <stdio.h> #include <math.h> /* converts to binary using logs */ int main() { long int decimalNUM = 0, binaryNUM = 0, exponentNUM = 0;
#include <stdio.h>
#include <math.h>
/* converts to binary using logs */
int main()
{
    long int decimalNUM = 0, binaryNUM = 0, exponentNUM = 0;
    printf("Enter a number to be converted to binary.\t");
    scanf("%ld", &decimalNUM);
    fflush(stdin);
    int origDEC = decimalNUM;
       while (decimalNUM > 0)
       {
          exponentNUM = (log(decimalNUM))/(log(2));
          binaryNUM += pow(10, exponentNUM);
          decimalNUM -= pow(2, exponentNUM);
       }
       printf("\nBINARY FORM OF %ld is %ld", origDEC开发者_开发问答, binaryNUM);
    getchar();
    return binaryNUM;
}

If STDIN is 4 it returns 99 and it should not. On IDEONE it returns 100. Why?

EDIT seems that any even number above two returns something with nines in it


Floating point operations like log are not exact. On my machine this code runs as expected (4 on STDIN gives 100).

One way you could do this, is by using the mod (%) operator with successive powers of two.


Works fine : http://ideone.com/PPZG5

As mentioned in the comments, your approach is really strange.

A general base-n conversion routine looks like:

void print_base_n(int val, int n) {
    if(val==0) { printf("0"); return; }
    else if(val < n) { printf("%d", val); return; }
    print_base_n(val/n, n);
    printf("%d", val % n);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消