gpt4 book ai didi

c - 64 位长整型参数

转载 作者:太空宇宙 更新时间:2023-11-04 06:49:49 25 4
gpt4 key购买 nike

我正在学习信息技术专业必修的计算机科学类(class)。所以我试图逐步理解这一点。我不知道我是怎么做错的或者不是预期的输出。

有什么建议或帮助吗?谢谢。

我的代码:

/**
* 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));

}

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

最佳答案

  1. 使用atoll得到 int64_t来自 argv[1]
  2. 使用(n&(1UL<<i))定义每一位是10
  3. 用var记录当前连续1位的个数

解释:

temp表示当前连续的1位计数

  1. 如果 n&(1UL<<i) == 1 , 当前位是 1 , 所以当前连续的 1 位计数加 1,所以 ++temp;

  2. 如果 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com