用C++语言设计一个算法,利用栈将一个正十进制整数转换为二进制数并输出
时间: 2024-09-24 12:27:25 浏览: 56
binary.rar_数值算法/人工智能_Visual_C++_
在C++中,我们可以使用栈数据结构来实现将十进制整数转换成二进制数的过程。下面是一个简单的示例算法:
```cpp
#include <iostream>
#include <stack>
using namespace std;
// Function to convert decimal to binary using stack
string decimalToBinary(int num) {
if (num == 0)
return "0";
stack<char> s;
while (num > 0) {
// Push the remainder onto the stack and divide by 2
s.push((char)(num % 2 + '0'));
num /= 2;
}
// Pop and concatenate the digits in reverse order
string binary = "";
while (!s.empty()) {
binary += s.top();
s.pop();
}
return binary;
}
int main() {
int input;
cout << "Enter a positive decimal number: ";
cin >> input;
string binary = decimalToBinary(input);
cout << "The binary representation of " << input << " is: " << binary << endl;
阅读全文