英文:
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 <iostream>
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 ? "0": "1");
//decimal number divided by 2
d /= 2;
}
//this function is going to return the binary representation
return decimal;
}
int main(){
int decimal;
cout<<"Input the decimal number: "<<endl;
cin>>decimal;
cout<<DecimaltoBinary(decimal)<<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 ? "0": "1") + decimal;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论