2012-09-09 84 views
-4
#include <stdio.h> 
int bitCount(unsigned int n); 

int main(void) { 
    printf ("# 1-bits in base 2 representation of %u = %d, should be 0\n", 0, bitCount (0)); 
    printf ("# 1-bits in base 2 representation of %u = %d, should be 1\n", 1, bitCount (1)); 
    printf ("# 1-bits in base 2 representation of %u = %d, should be 17\n", 2863377066u, bitCount(2863377066u)); 
    printf ("# 1-bits in base 2 representation of %u = %d, should be 1\n", 268435456, bitCount(268435456)); 
    printf ("# 1-bits in base 2 representation of %u = %d, should be 31\n", 4294705151u, bitCount(4294705151u)); 
    return 0; 
} 

int bitCount(unsigned int n) { 
    /* your code here */ 
} 

你已经决定要你上面的位计数程序从命令行添加功能

# ./bitcount 17 
2 
# ./bitcount 255 
8 
# ./bitcount 10 20 
too many arguments! 
# ./bitcount 
[the same result as from part a] 

我得到,我们必须包括以上低于return 0 printf("too many arguments!")工作,但它不断给我一个错误。 任何人都可以帮助我吗?

+3

这看起来不像c#.. – Thousand

+0

<您的代码在这里>部分看起来像c# – wildplasser

+0

这是否应该有家庭作业标签? – James

回答

1

修改您main接受申报参数:

int main(int argc, char * argv[]) { 

确保参数计数(argc)是2(一个用于指令,一个用于参数):

if(argc < 2) { 
    // Give some usage thing 
    puts("Usage: bitcount <whatever>"); 
    return 0; 
} 

if(argc > 2) { 
    puts("Too many arguments!"); 
    return 0; 
} 

然后,使用类似atoi的东西将参数argv[1]解析为int

printf("%d\n", bitCount(atoi(argv[1]))); 

(这在stdlib.h,顺便说一下。 )

+0

它看起来像程序应该有原始行为,如果没有参数提供。因此,不要在argc <2上执行保存操作,而应该执行printfs列表 – James