0

我想我差不多明白了,但我觉得我在绕圈子试图解决这个问题。在不使用字符串或数组的情况下输出 cout 的挑战。我以数字 56 为例,56 应该等于 111000,但情况并非如此,因为它一直到 7 为止,然后数字等于 number*2 + number%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

4 回答 4

2

您可以使用二元运算符 & 来检查单个位是 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;
    }
}
于 2013-05-18T06:05:46.100 回答
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 的打印

于 2013-05-18T07:10:14.787 回答
0

我最近遇到了这类问题。此代码示例最多可处理 10 个二进制数字(根据问题指南)并一直提示输入,直到输入 0(标记值)。这当然可以改进,但数学是正确的:

#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);
}
于 2013-10-06T17:10:06.273 回答
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;
}

虽然在 CI 中问过用过 C++。我使用的逻辑是,如果您必须将十进制转换为二进制,我们必须找到数字中包含的 2 的最大幂,当加 1 时,该数字将成为所需二进制的位数.. 最左边的数字是可用的最高位数2 的幂(例如 8 中 2 的最高幂是 3 和 1 这样可用)...然后从数字中减去这个和(例如 8-8 = 0)并搜索下一个最高可用幂的 2 等上。

于 2018-08-01T18:03:35.807 回答