Итак, вот моя проблема: у меня (как я думаю) есть достойный раздел кода, он работает для большинства чисел, которые я вставлял. Однако, когда я помещал 2^x
число (например, 32
или 64
), это возвращает 10
а не 10000000
, что явно неверно. Любая помощь будет принята с благодарностью.
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
//void thework(unsigned int num); /*was going to take this another direction and decided not to*/
int main(){
int num;
int por;
int mun;
por = 64;
cout<<"imput a number you want to convert to binary"<<endl;
cin>>num;
start:
if(num < pow(2.0,por)){ /*just to get the power widdled down to size*/
por--;
goto start;
}
/*part 2 is the "print 1" function, part 2 is the "print 0 and return to part 1, or kill section */
p2:
if((num >= (pow(2.0,por)))&&(num != 0)){
cout<<"1";
num -= pow(2,por);
por--;
goto p2;
}
p3:
if((num < pow(2,por))&&(num > (-1))){
mun=num;
if((mun -= pow(2.0,por)) > 0){
cout<<"1";
num -= pow(2.0,por);
goto p2;
}
if((mun -= pow(2.0,por)) > 0){
cout<<"0";
num -= pow(2.0,por);
por--;
goto p2;
}
return 0;
}
Здесь другой подход, некоторые важные детали
#include <iostream>
using namespace std;
int main(int argc,char *argv[])
{
int num;
cout << "input a number you want to convert to binary" << endl;
cin >> num;
for(int j = sizeof(num)*8 - 1;j >= 0;j--)
{
if(num & (0x1 << j)) cout << "1";
else cout << "0";
}
cout << endl;
return 0;
}
int
иdouble
вызывает эту проблему. и еще одна вещь,2^64
которая имеет64
бита, также сравнивается сint
которая имеет32
бита. Кстати, почему бы не использовать%
и/
или битовые операции для печати двоичного файла?1 << (por - 1)