我正在寻找将十进制转换为二进制的代码,而我偶然发现了这一点:
#include <iostream>
using namespace std;
int main()
{
int num;
cout << "Please enter a number: ";
cin >> num;
if (num > 0) {
int i = 1;
while (i <= num)
i *= 2;
i /= 2;
do {
if (num >= i) {
cout << '1';
num -= i;
}
else
cout << '0';
i /= 2;
} while (i > 0);
cout << "";
}
else
cout << '0';
}
我似乎无法理解此循环的逻辑 while (i <= num)
i *= 2;
i /= 2;
我试图将cout放在等式之间以查看过程 while (i <= num)
cout << i;
cout << "A";
i *= 2;
cout << i;
cout << "B";
i /= 2;
cout << i;
cout << "C";
但结果为111111111111111111 ...并没有停止有人可以解释一下吗
最佳答案
在理解任何算法时,请用铅笔和纸逐一验证该代码的每一步。选择一个小的测试用例,例如10
作为输入,您知道它具有1010
的二进制表示形式,并逐步执行四个迭代来了解正在发生的情况。
如果这样做,您将找到以下内容:
while (i <= num) /* find next power-of-two greater than num */
i *= 2;
然后减少2的幂以消除任何前导零作为输出,例如 i /= 2; /* divide by two, 1st power-of-two less than num */
这样可以确保i
比num
小二分之一。现在看一下do .. while (i > 0);
循环中的算法(重新排列和缩进,这样更有意义): do { /* loop until i <= 0 */
if (num >= i) { /* is num >= i? */
std::cout << '1'; /* if so, output character '1' */
num -= i; /* reduce num by i */
}
else /* otherwise */
std::cout << '0'; /* output '0' character if num < i */
i /= 2; /* divide i by 2 (integer division intentional) */
} while (i > 0);
该算法很简单。i
是比num
小的下一个2的幂,因此有条件if (num >= i)
将测试为true ,以确保第一个字符输出为'1'
。然后在第一次迭代中将num
减少i
(在num = 10;
的情况下),i = 8
,以便num -= i;
保留num = 2
。 i
除以2
剩下i = 4
。 '0'
,然后将i
除以2
再除以i = 2
,即i = num = 2
。 '1'
,num
减少为0
,i
减少为1
,您再次循环。 '0'
并将i
减小为零,退出循环。 输出
10
的正确二进制表示形式:1010
如果根据else
重构代码以消除不必要的num >= 0
条件,则只需处理否定或零的情况并返回。这样可以节省整个代码的完整缩进级别。综上所述,您可以将相同的代码重写为:#include <iostream>
int main()
{
int num, i = 1;
std::cout << "Please enter a number: ";
std::cin >> num;
if (num <= 0) {
std::cout << "0\n";
return 0;
}
while (i <= num) /* find next power-of-two greater than num */
i *= 2;
i /= 2; /* divide by two, 1st power-of-two less than num */
do { /* loop until i <= 0 */
if (num >= i) { /* is num >= i? */
std::cout << '1'; /* if so, output character '1' */
num -= i; /* reduce num by i */
}
else /* otherwise */
std::cout << '0'; /* output '0' character if num < i */
i /= 2; /* divide i by 2 (integer division intentional) */
} while (i > 0);
std::cout << '\n'; /* tidy up with newline */
}
(注意:请参阅Why is “using namespace std;” considered bad practice? -学习良好的习惯比以后打破坏习惯要容易得多。)示例使用/输出
$ ./bin/binary_conversion
Please enter a number: 10
1010
要么$ ./bin/binary_conversion
Please enter a number: 126
1111110
要么$ ./bin/binary_conversion
Please enter a number: 170
10101010
该代码工作正常。仔细检查一下,如果您还有其他问题,请告诉我。
关于c++ - 将十进制转换为二进制的C++循环的逻辑是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63626238/