我发布了 this两天前,但由于我的问题已更改为其他问题,现在我需要有关代码中新问题的帮助,我认为发布新帖子是可以的。如果我错了,请关闭这个问题;我是社区的新手,不想惹任何麻烦。我只是想得到一些帮助来解决我的问题。
我收到了一些反馈:我知道这段代码有两个问题:我需要检查用户的输入是否在范围内(0~2^32 - 1;如果不在范围内,它收到“警告”消息),我需要检查负数(这些应该收到“无效”警告)。但我完全被难住了。我能否在使用我的代码来完成上述两件事时获得更多帮助?
更新:我认为这段代码终于成功了。如果我忽略了编译后未显示的错误,请告诉我。谢谢!
#include <stdio.h>
int main() {
long long int num;
int count = 0;
printf("Please enter an integer: ");
scanf("%lld", &num);
if (num >= 0 && num <= 4294967295) {
while(num){
count += num & 1;
num >>= 1;
}
printf("%d\n", count);
} else {
printf("Warning: this is not a valid integer\n");
}
return 0;
}
最佳答案
使用 scanf might be problematic and dangerous .更好的方法是使用 fgets 从用户那里获取输入,然后使用 strtoul/strtoul 将字符串转换为整数。
关于C 帮助 - 当用户输入无符号整数时检查范围和负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46333297/