我想要的是接受一个整数,并在方法中将其转换为二进制,接近下面代码中显示的方法。但是,我想将数字转换为二进制,就像它在小数点后面一样。因此,如果我输入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;
}
答案 0 :(得分: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来自here。由于浮点不精确,我的解决方案并不完美,但它适用于大多数情况?
答案 1 :(得分: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;
}
答案 2 :(得分:0)
Archive for the ‘C Programming’ Category 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();
}