Thread: # of ones in Binary representation

  1. #1
    Registered User
    Join Date
    Nov 2001
    Posts
    3

    Question # of ones in Binary representation

    Can someone tell me why my program does not compile?


    __________________________________________________ _

    int bitcnt ( float n );

    #include<stdio.h>

    int main ( void )
    {
    float n;

    for (;
    {
    printf("Give a positive integer ( <=0 to stop ) : ");
    scanf("%f", &n);
    if (n <= 0) break;
    printf("Number of ones in bit representation of %f : %.2f\n",
    n, bitcnt(n));
    }

    return 0;
    }
    int bitcnt ( float n )
    {
    int cnt = 0;
    float work;

    for (work = n; work > 0; work /= 2)
    cnt += (work % 2);

    return cnt;
    }

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    18
    why are you floating n if you want them to enter an integer?

  3. #3
    Registered User
    Join Date
    Nov 2001
    Posts
    3
    Ok, I changed floats to int.....and its works correctly.


    int bitcnt ( int n );

    #include<stdio.h>

    int main ( void )
    {
    int n;

    for (;
    {
    printf("Give a positive integer ( <=0 to stop ) : ");
    scanf("%d", &n);
    if (n <= 0) break;
    printf("Number of ones in bit representation of %d : %d\n",
    n, bitcnt(n));
    }
    return 0;
    }

    int bitcnt ( int n )
    {
    int cnt = 0;
    int work;

    for (work = n; work > 0; work /= 2)
    cnt += (work % 2);

    return cnt;
    }
    ------------------------------------------------------------------------------------
    Thanks for the hint.

  4. #4
    Sayeh
    Guest

    Bit counting

    This is just a general, non-all-purpose bit counter:


    int BitterGitter(int);


    int BitterGitter(int num)
    {
    int bits = 0;
    int i;

    while(i<16)
    {
    bits += (0x0001 & num);
    num >>= 1;

    i++;
    };

    return(bits);
    }


    enjoy.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Binary representation in C
    By @nthony in forum C Programming
    Replies: 25
    Last Post: 11-10-2007, 12:43 AM
  2. Replies: 3
    Last Post: 11-25-2006, 04:14 PM
  3. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  4. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM
  5. Binary representation similar to 0xFF ?
    By DougDbug in forum C++ Programming
    Replies: 3
    Last Post: 01-10-2003, 12:08 PM