-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 程序从命令行运行

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

我知道我们必须在 printf("too many arguments!")下面包含以上内容,return 0但它一直给我一个错误。谁能帮我这个?

4

1 回答 1

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;
}

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

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

stdlib.h顺便说一下,它在 中。而且您可能还想做一些错误检查。)

于 2012-09-09T21:08:05.820 回答