欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

十进制转化为二进制

程序员文章站 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