我正在学习计算机科学课程,这是我的信息技术专业所必需的。因此,我试图逐步了解这一点。我不知道我做错了什么,或者不是预期的输出。
有什么建议或帮助吗?谢谢。
我的代码:
/**
* 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));
}
当我运行编译以查看输出时,但与示例输出匹配似乎并不正确。
答案 0 :(得分:2)
atoll
从int64_t
获取argv[1]
(n&(1UL<<i))
定义每个位是1
或0
解释:
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;
}
答案 1 :(得分:1)
您发布的内容会导致编译错误:
main.c:52:44: error: ‘n’ undeclared (first use in this function) printf("count = %d, largest run = %d\n", n, count(n)); ^
如代码中的注释所建议,您需要添加以下行:
int n = n = atoll(argv[1]);
修改您的main
函数,使其看起来像这样:
int main (int argc, char *argv[])
{
if(argc < 2)
{
printf ("Usage: p3 <int>\n");
}
else
{
int n = atoll(argv[1]);
printf("count = %d, largest run = %d\n", n, count(n));
}
return 0;
}
如果您的count
函数应该return
中1
位的数量n
,则您的实现将无法正常工作。将while
正文更改为以下内容:
ret += x % 2;
x /= 2;