我在修信息技术专业的计算机科学课程。所以我试图一步一步地理解这一点。我不知道我怎么做错了,也不知道预期的结果是什么。
有什么建议或帮助吗?谢谢您。
我的代码:

/**
 * Create a function called count that takes a 64 bit long integer parameter (n)
 * and another integer pointer (lr) and counts the number of 1 bits in n and
 * returns the count, make it also keep track of the largest run of
 * consecutive 1 bits and put that value in the integer pointed to by lr.
 * Hint: (n & (1UL<<i)) is non-zero when bit i in number n is set (i.e. a 1 bit)
 */


/* 1 point */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

int count (uint64_t n)
{
  int ret = 0;
  long x = n;
  if (x < 0)
    x = -x;
  while (x != 0)
    {
      ret += x % 2;
      x /= 2;
    }
  return ret;     //done summing when n is zero.
}

/**
 * Complete main below and use the above function to get the count of 1 bits
 * in the number passed to the program as the first command line parameter.
 * If no command line parameter is provided, print the usage:
 *   "Usage: p3 <int>\n"
 * Hints:
 * - Use atoll to get a long long (64 bit) integer from the string.
 * - Remember to use & when passing the integer that will store the longest
 *   run when calling the count function.
 *
 * Example input/output:
 * ./p3 -1
 * count = 64, largest run = 64
 * ./p3 345897345532
 * count = 17, largest run = 7
 */
int main (int argc, char *argv[])
{
  if (argc < 2)
    {
      printf ("Usage: p3 <int>\n");
    }
  int n = atoll(argv[1])
  printf("count = %d, largest run = %d\n", n, count(n));

}

当我运行编译以查看输出时,但它似乎与示例输出不匹配。

最佳答案

使用atollint64_t获取argv[1]
使用(n&(1UL<<i))定义每个位是10
使用var记录当前连续的1位计数
说明:
temp表示当前连续1位计数
如果n&(1UL<<i) == 1,则当前位为1,因此当前连续1位计数加1,所以++temp;
如果n&(1UL<<i) == 0,当前位为0,则当前连续1位计数为0,因此temp = 0;
以下code可以工作:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

int count(int64_t n, int* lr) {
    *lr = 0;

    int temp = 0;
    int ret  = 0;

    for (int i = 0; i != 64; ++i) {
        if (n&(1UL<<i)) {
            ++ret;
            ++temp;
            if (temp > *lr)
                *lr = temp;
        } else {
            temp = 0;
        }
    }
    return ret;
}

int main (int argc, char *argv[]) {
    if (argc != 2) {
        printf ("Usage: p3 <int>\n");
        return -1;
    }

    int64_t n = atoll(argv[1]);
    int k;

    int sum = count(n, &k);

    printf("count = %d, largest run = %d\n", sum, k);

    return 0;
}

关于c - 64位长整数参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53090485/

10-11 23:40