十进制转化为二进制
程序员文章站
2022-07-15 08:21:24
...
错误代码:
#include <iostream>
using namespace std;
void binary(int);
void main(void) {
int number;
cout << "Please enter a positive integer: ";
cin >> number;
if (number < 0)
cout << "That is not a positive integer.\n";
else {
cout << number << " converted to binary is: ";
binary(number);
cout << endl;
}
}
void binary(int number) {
int remainder;
if(number <= 1) {
cout << number;
return;
}
remainder = number%2;
cout << remainder; //先输出reminder会导致最后得出的数字刚好颠倒
binary(number >> 1);
}
正确代码:
#include <iostream>
using namespace std;
void binary(int);
void main(void) {
int number;
cout << "Please enter a positive integer: ";
cin >> number;
if (number < 0)
cout << "That is not a positive integer.\n";
else {
cout << number << " converted to binary is: ";
binary(number);
cout << endl;
}
}
void binary(int number) {
int remainder;
if(number <= 1) {
cout << number;
return;
}
remainder = number%2;
binary(number >> 1);
cout << remainder; //递归调用,栈顶数字先出来
}
加标注的两行代码顺序很重要
转载于:https://my.oschina.net/zshuangyan/blog/133250
上一篇: Python 遍历数组的方法
下一篇: 十进制转化为二进制