c - 为什么我的关于反转位的 C 代码不起作用?
问题描述
我正在编写代码来反转一个无符号整数,其位相同但顺序相反。我的代码在接受用户输入时不会停止运行。我究竟做错了什么?
#include <stdio.h>
unsigned int reverse_bits(unsigned int n);
int main(void) {
unsigned int n;
printf("Enter an unsigned integer: ");
scanf("%u",&n);
printf("%u\n",reverse_bits(n));
return 0;
}
unsigned int reverse_bits(unsigned int n) {
unsigned int reverse = 0;
while(n>0) {
reverse <<= 1;
if((n & 1) == 1) {
reverse = reverse^1;
}
}
return reverse;
}
解决方案
在您的程序中,while 条件是检查 n 是否大于零。但是,在循环内部,没有修改 n 的操作。所以请尝试使用它。它会起作用的。
unsigned int reverse_bits(unsigned int n) {
unsigned int reverse = 0;
while (n>0) {
reverse <<=1;
if((n & 1) == 1) {
reverse = reverse | 1;
}
n=n>>1;
}
return reverse;
}
推荐阅读
- c# - EF Core 3.1 Intellisense 不在 Linq 语句的 Where 子句中显示表列
- centos - 升级后我得到这个 puppet 6 错误是什么?
- python - 在列中插入条件行
- tensorflow - Google Colab 上的 Tensorboard 返回一个链接,但没有执行任何操作
- tsql - 为什么 T-SQL TRY/CATCH 如此有限?
- sql - 有没有办法查看 SQL 表达式的类型?
- fastlane - Fastlane 插件应用中心给出提供的 app_name: 'helloworldtest" 格式无效
- windows - 如何将图标添加到 dotnet 桌面(Windows)应用程序?
- python - SyntaxError:无效的语法 - 使用 celery 时从可迭代中产生
- arrays - 写入时间长,使用 Dask 从 hdf5 文件到 numpy 堆栈的读取时间短