我想将一系列整数转换为十进制。我知道程序但是如何将所有整数作为一个二进制数?
输出必须如下:
Enter first binary digit: 0
Enter second binary digit: 0
Enter third binary digit: 0
Enter fourth binary digit: 0
0000 = 0
以下是我编写此任务的方法:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<conio.h>
int main(void)
{
int a[100];
int n, dec = 0; int power(int, int);
long int binaryNumber, decimalNumber = 0, j = 1, remainder;
printf("Enter first binary number: ");
scanf("%ld", &a[1]);
printf("Enter second binary number: ");
scanf("%ld", &a[2]);
printf("Enter third binary number: ");
scanf("%ld", &a[3]);
printf("Enter fourth binary number: ");
scanf("%ld", &a[4]);
for (int i = 0;i<n;i++)
{
scanf("%d", &a[i]);
}
for (int i = (n - 1);i >= 0;i--)
{
dec = (a[i] * power(2, j)) + dec;
j++;
}
printf("binary number of decimal is %d", dec);
return 0;
}
答案 0 :(得分:3)
嗯,这是简单的数学。第一个二进制数字是2 ^ 0,第二个2 ^ 1,第三个2 ^ 2,...
number = first * 1 + second * 2 + third * 4 + forth * 8;
答案 1 :(得分:-1)
//binary to decimal converter
long int bin2dec(long int binary_number,int i){
if(binary_number == 0)
return 0;
else
return ((binary_number%10)*pow(2,i) + bin2dec(binary_number/10,++i));
}