- //二进制数转换为十进制数
- #include"stdafx.h"
- #include<iostream>
- //#include<string.h>
- //#include<process.h>
- using namespace std;
- void main(){
- int i, bitv, w=1, value = 0;//value累加和、bitv位值(0或1)、w权值
- char a[20];
- cout << "Enter a bit binary number(less than 20 bit):"<<endl;
- cin >> a;
- for (i = strlen(a)-1; i >= 0; i--){
- bitv = a[i];
- if (bitv == ‘1‘)//注意字符串形式
- value += w;
- else
- if (bitv !=‘0‘)
- { //判断输入正误
- cout << "enter error!";
- exit(0);
- }
- w *= 2; //更换权值
- }
- cout << " ------------ - result------------ -" << endl;
- cout << a << "(2)="<<value << "(10)"<<endl;
- }
- -----------------------------------------------------------------------------------
//十进制数转换为二进制数(逐次除二,倒取余数)
- #include"stdafx.h"
- #include<iostream>
- using namespace std;
- void main(){
- int n,bitv,i=0;
- int a[20];
- cout << "Please enter a integer(10):"<<endl;
- cin >> n;
- while (n >= 1){
- bitv = n % 2;
- a[i] = bitv;
- i++;
- n/=2;
- }
- cout << n << "(10)=";
- for (int j = i - 1; j >= 0; j--){
- cout << a[j];
- }
- cout << "(2)"<<endl;
- }
时间: 2024-10-03 10:51:48