如何使写入输出方向相反 (C++)

How to make writing output in opposite direction (C++)?

本文关键字:C++ 方向 何使写 输出 输出方      更新时间:2023-10-16

我创建了一个简单的十进制到二进制程序。假设我输入数字 8。它写回 0001我希望它是 1000

我该怎么做?

代码在这里:

using namespace std;
int translating(int x);
int main()
{
    int x;
    int translate;
    cout << "Write a number: ";
    cin >> x;
    cout << endl;
    translate = translating(x);
    cout << endl;
    cout << endl;
    return 0;
}
int translating(int x)
{
    if (x == 1)
    {
        cout << "1";
        return 0;
    }
    if ((x % 2)==1)
    {
        cout << "1";
        return (translating((x-1)/2));
    }
    else
    {
        cout << "0";
        return (translating(x/2));
    }
}

不要直接写入输出,而是先将其写入临时字符串,然后从最后一个字符遍历该字符串到第一个字符。

很简单,很简单,你会踢自己。只需颠倒输出语句和递归函数调用的顺序即可。还修复了一个错误。

void translating(int x)
{
    if (x < 2)
    {
        cout << x;
        return;
    }
    if ((x % 2)==1)
    {
        translating((x-1)/2);
        cout << "1";
    }
    else
    {
        translating(x/2);
        cout << "0";
    }
}