I'm trying to make a decimal to binary converter and the result is printing right-to-left and the correct way is left-to-right

huangapple go评论71阅读模式
英文:

I'm trying to make a decimal to binary converter and the result is printing right-to-left and the correct way is left-to-right

问题

我正在尝试自己制作一个二进制转十进制的转换器。我尝试过使用数组,但由于每个数字的二进制表示长度不确定,我发现很难使用它们。所以现在我尝试使用三元运算符,它可以工作,但结果是从左到右显示,而正确答案应该是从右到左。是否有人有更好的方法或办法来解决这个问题?

#include <iostream>

using namespace std;

//将十进制转换为二进制的函数
string DecimaltoBinary(int d){

//将存储二进制表示的变量
string decimal;

    //不断除以2,直到变量d达到0
    while(d!=0){

        //变量decimal将存储二进制表示
        decimal += (d % 2 == 0 ? "0" : "1");

        //将十进制数除以2
        d /= 2;
    }
    //此函数将返回二进制表示
    return decimal;
}

int main(){
    
    int decimal;

    cout << "输入十进制数字: " << endl;

    cin >> decimal;

    cout << DecimaltoBinary(decimal) << endl;
    
    return 0;
}

这是您提供的代码的翻译部分,代码本身没有进行翻译。如果您有其他问题或需要进一步帮助,请随时告诉我。

英文:

I'm trying to make a binary-to-decimal converter on my own. I tried arrays, but with unspecified lengths of binary representations for each number, I found it hard to use them. So now I'm trying with a ternary operator, and it works but the result is showing left-to-right when the correct answer should be right-to-left. Do anyone have a better method or way to make this thing right?

#include &lt;iostream&gt;

using namespace std;

//function that converts decimal to binary
string DecimaltoBinary(int d){

//variable that is going to store the binary representation
string decimal;

    //keep dividing by 2 till variable d reaches 0
    while(d!=0){

        //variabable decimal is going to store the binary representation
        decimal += (d % 2 == 0 ? &quot;0&quot;: &quot;1&quot;);

        //decimal number divided by 2
        d /= 2;
    }
    //this function is going to return the binary representation
    return decimal;
}

int main(){
    
    int decimal;

    cout&lt;&lt;&quot;Input the decimal number: &quot;&lt;&lt;endl;

    cin&gt;&gt;decimal;

    cout&lt;&lt;DecimaltoBinary(decimal)&lt;&lt;endl;
    
    return 0;
}

答案1

得分: 1

decimal = (d % 2 == 0 ? "0" : "1") + decimal;
英文:

The simplest solution using your existing code is just to reverse the assignment:

decimal = (d % 2 == 0 ? &quot;0&quot;: &quot;1&quot;) + decimal;

huangapple
  • 本文由 发表于 2023年2月19日 08:25:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75497268.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定