简体   繁体   English

以正确的顺序从十进制转换为二进制

[英]Converting from decimal to binary in the right order

i'm a complete noob in c++ and we had to do a programm in school that calculates the cross sum of a number and then convert this number to a binary number.我是 c++ 中的一个完整的菜鸟,我们必须在学校做一个程序来计算一个数字的交叉和,然后将该数字转换为二进制数。

The problem I have now is that the binary number is in reverse order.我现在遇到的问题是二进制数的顺序相反。 I want to add the digits into an array and then cout the array from right to left, but I do not have any Idea how to do it.我想将数字添加到数组中,然后从右到左计算数组,但我不知道该怎么做。 :/ :/

Could someone explain / show me how to do it?有人可以解释/告诉我怎么做吗?

And I am using the do while loops because that was the requirement for the task...我正在使用 do while 循环,因为这是任务的要求......

int main()
{
    int digit, sum = 0, rem;

    cout<<"Enter a positive digit" << endl;
    cin >>  digit;

    do {
        sum= sum + (digit%10); 
        digit /= 10;
    }
    while (digit!= 0);

    cout <<"Cross sum" << sum << endl; 

    do {
        rem = sum % 2;
        sum /= 2;
        cout << "Decimal in Binary: " << rem << endl;
    }
    while(sum>0);

    return 0;
}

This function will print decimal to binary in right order:此 function 将以正确的顺序将十进制打印为二进制:

void decToBin(int n) {
    if (n == 0) {
        return;
    }
    decToBin(n / 2);
    cout << n % 2;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM