两天前我发布了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;
}
发布于 2017-09-20 16:09:53
使用scanf might be problematic and dangerous。更好的方法是使用fget从用户获取输入,然后使用strtoul/strtoul将字符串转换为整数。
https://stackoverflow.com/questions/46333297
复制相似问题