#include <iostream>
#include <Windows.h>
#include <string>
using namespace std;
int main() {
int n;
int ret[32];
int i = 0;
cout << "请输入一个正整数:";
cin >> n;
if (n < 0) {
cout << "需要输入一个正整数!" << endl;
system("pause");
return 1;
}
while (n != 0) {
ret[i] = n % 2;
n = n / 2;
i++;
}
for (i--; i >= 0; i--) {
cout << ret[i] ;
}
cout << endl;
system("pause");
return 0;
}
进化版:
#include <iostream>
#include <string>
#include <windows.h>
using namespace std;
int main() {
int n;
int ret[32];
int i = 0;
while (1){
system("cls"); //清除屏幕
cout << "请输入一个正整数:";
cin >> n;
if (n > 0) {
break;
}
else {
cout << "需要输入一个正整数!" << endl;
system("pause");
}
}
while (n != 0) {
ret[i] = n % 2;
n = n / 2;
i++;
}
for (i--; i >= 0; i--) {
cout << ret[i];
}
cout << endl;
system("pause");
return 0;
}