0

我想要的是接受一个整数,并以一种接近于下面代码中显示的方法的方法将其转换为二进制。但是,我想将数字转换为二进制,就好像它在小数点之后一样。因此,如果我得到 625 作为输入,那么我希望它转换为 101。

给定代码:

#include <iostream>
using namespace std;

int decTobinary(int);

int main(){
    cout << "Enter a number = ";
    int num;
    cin >> num; 
    int answer = decTobinary(num);
    cout << "answer: " << answer << endl"
    return 0;
}
int decTobinary(int x) {
    if (x==0)
    return 0;
    return 10 * decTobinary(x/2) + x % 2;
}
4

3 回答 3

0

我将它一起破解,所以它并不漂亮,但它提供了您正在寻找的输出:

#include <iostream>

float intToDecimalPoint(float f)
{
    if((f / 10.0f) <= 1.0f)
        return f/10.0f;
    else
        return intToDecimalPoint(f/10.0f);
}

void decTobinary(int x)
{
    if (x==0)
        return;

    float decimalPoint = intToDecimalPoint(float(x));
    if(decimalPoint*2.0f >= 1.0f)
    {
        std::cout << 1;
        int newX = int((decimalPoint*2.0f - 1.0f)*(float(x)/decimalPoint));
        return decTobinary(newX);
    }
    else
    {
        std::cout << 0;
        decTobinary(x*2);
    }
}

int main()
{
    std::cout << "Enter a number = ";
    int num;
    std::cin >> num; 
    std::cout << "answer: ";
    decTobinary(num);
    std::cout << std::endl;


    std::cin.get();
    std::cin.get();
    return 0;
}

Algo 来自这里。由于浮点不精确,我的解决方案并不完美,但它应该适用于大多数情况?

于 2013-07-02T06:34:27.037 回答
0

你可以试试

#include <iostream>
#include <vector>
#include <cmath>

using namespace std;

int GetNumberOfDigits (int i)
{
    return i > 0 ? (int) log10 ((double) i) + 1 : 1;
};

void function(int number, vector<int> &convert)    {
    double remainder = number/pow(10,GetNumberOfDigits(number));
    do
    {
        remainder = remainder*2;
        convert.push_back(int(remainder));
        remainder = remainder - int(remainder);
    }
    while(remainder != 0);
};

int main()  {
    vector<int> solution;
    int n;
    cout<<"Enter number: ";
    cin>>n;
    function (n, solution);
    for(int index = 0; index < solution.size(); index++) std::cout<<solution[index];
    return 1;
}
于 2013-07-02T07:07:24.467 回答
0

“C 编程”类别的存档 http://www.programmingclub.in/category/c-programming/

#include<stdio.h>

#include<conio.h>

void main()

{

  int a[10],n,i,j=0;

  printf(“Enter the Number: “);

  scanf(“%d”,&n);

  while(n>0)

  {

             i=n%2;

             a[j++]=i;

             n=n/2;

            }

  j–;

  printf(“\nBinary form is: \n”);

  while(j>=0)

  {

             printf(“%d”,a[j]);

             j–;

            }

            getch();

  }
于 2013-11-17T19:09:28.473 回答