Decimal to binary...
I've written a program witch converts dec to bin:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int i,a,liczba,x[32];
std::cout << "Wprowadz liczbe:";
std::cin >> liczba;
for ( i=0 ; liczba>0 ; i++ , liczba=liczba/2 )
{
if (liczba%2==0) x[i]=0;
else
{
x[i]=1;
liczba=liczba-1;
}
}
a=i;
for ( i=0 ; i<a ; i++ )
cout << x[i];
system("pause");
return 0;
}
|
Everything is ok, but the result is display backwards, so i decidet to change my program like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int i,a,liczba,x[32];
std::cout << "Wprowadz liczbe:";
std::cin >> liczba;
for ( i=0 ; liczba>0 ; i++ , liczba=liczba/2 )
{
if (liczba%2==0) x[i]=0;
else
{
x[i]=1;
liczba=liczba-1;
}
}
a=i;
for ( i=a ; i>0 ; i-- )
cout << x[i];
system("pause");
return 0;
}
|
I was sure it would work but the result is strange, and I don't know what to do with it. Could anyone help me?
EDIT: Sory, english isn't my countrys language so i use it only on forums like this one.
Last edited on
line 22 should be a=i-1;
line 23 the condition should be i>=0;
Topic archived. No new replies allowed.