C十进制到二进制没有数组

时间:2013-05-18 06:00:15

标签: c++ arrays string binary decimal

我想我几乎得到了它,但我觉得我是在试图解决这个问题。 在不使用字符串或数组的情况下输出cout的挑战。我把数字56作为一个例子,56应该等于111000这不是这种情况,因为它经过罚款直到7然后数字等于数字* 2 +数字%2使它等于15并输出所有1。 Idk了,这让我开到了月球之后。

#include <iostream>

using namespace std;

int main()
{
int number = 0;
int n = 1;
int x = n;
cin>>number;
cout<<n%2;
while(n <= number)
{
    if(n%2 == 0)
    {
        n = n*2;
        cout<<0;
    }
    else
    {
        n = n*2 + n%2;
        cout<<n%2;
    }
}
}

4 个答案:

答案 0 :(得分:2)

您可以使用二元运算符&amp;检查单个位是1还是0。

for (int i=512; i>0; i/=2) {
    cout << ( ( number & i ) != 0 ) ;
}

请注意,这将打印前导0。 另外,我假设你只想打印正整数。

替代:

for (int i=512; i>0; i/=2) {
    if (number >= i) {
        cout << 1;
        number -= i;
    } else {
        count << 0;
    }
}

答案 1 :(得分:0)

您可以使用递归

void decimal_to_binary(int decimal)
{
    int remainder = decimal % 2;
    if (decimal < 1)
        return;
    decimal_to_binary(decimal / 2);
    cout << remainder;
}

此函数将取小数,当除以2时得到余数。在函数再次调用之前,它检查小数是否小于1(可能为0)并返回执行1和0的打印< / p>

答案 2 :(得分:0)

我最近有这样的问题分配给我。此代码示例最多可处理10个二进制数字(根据问题指南)并继续提示输入,直到输入0(sentinel值)。这肯定可以改进,但数学是正确的:

#include <iostream>
#include <cmath>
using namespace std;

int main ()
{
 //Declare Variables
 int inputValue = 0;
 int workingValue = 0;
 int conversionSum = 0;

 //Begin Loop
 do{
     //Prompt for input
     cout << "Enter a binary integer (0 to quit): ";
     cin >> inputValue;

     //Reset Variables
     workingValue = inputValue;
     conversionSum = 0;

    //Begin processing input
    //10 digits max, so 10 iterations

    for (int i=0; i<10; i++) {
        //Check for non-binary entry
        if ((workingValue % 10) != 1 && (workingValue % 10 != 0)){
            cout << "Invalid!\n";
            workingValue = 0;
            conversionSum = 0;
            break;
           }

        //check to see if 2^i should be added to sum
        if (workingValue%2 == 1){
            conversionSum += pow(2,i);
            workingValue--;
           }
        //divide by 10 and continue loop
        workingValue= workingValue / 10;
    }

    //output results
    cout << "converted to decimal is: " << conversionSum << endl;

 }while (inputValue != 0);
}

答案 3 :(得分:0)

#include<iostream>
#include<cmath>
using namespace std;

int main()
{
    cout << "enter a number";
    int number, n, a=0;
    cin >> number;
    n = number;
    do 
    {
        n=n/2;
        a=a+1;  
    }
    while (n>=1);
    cout << "a is" << a;
    int c = a;
    int b = a;
    cout << "binary is";
    for(int i=0; i<=c; i++)
    {
        int k = number / pow(2,b);
        cout << k;
        number = number - k * pow(2,b);
        b = b-1;
    }
    return 0;
}

尽管在C语言中我使用过C ++。我已经使用了逻辑,如果必须将十进制转换为二进制,我们必须找到数字中包含的2的最大乘方,当乘以1时就成为所需二进制的位数。.最左边的数字是最高可用位数。 2的幂(例如8的2的最高幂是3且1可用)...然后从数字中减去(例如8-8 = 0)并搜索下一个2的最高可用幂的数上。