我需要帮助在c中编写二进制转换程序。我需要一种方法来增加数组的大小,具体取决于二进制数中的位数,将1和0放在另一个数组中,并在第一个数组中添加数字以获得十进制转换后的数字。我正在学习c编程作为我的第一门编程语言。 这是我到目前为止所拥有的
#include <stdio.h>
int main (void)
{
printf("Please input binary number to convert to decimal.");
Scanf("%d");
for(i=2;i<= /*number of integers in binary number*/;i++ )
{
int i
char conversiontable [2][i] ={
/*array1*/{'1','2',},
/*array2*/{}
};
/*inputs 110001101*/
/*increase size of array1 according to number of 1's and 0's in the binary number*/
/*fill empty slots in array 1 with the output of (2^2)2 starting in slot 3 and add 1 to the number outside the parenthesis for each slot*/
/*put binary number in array 2*/
/*add together the numbers in array 1 in correspondence to wherever there is a 1 in array 2*/
/*example*/
/*1,2,4,8,16,32,64,128,256*/
/*1,1,0,0, 0, 1, 1, 0, 1*/
/*1+2+32+64+256=355*/
/*outputs 355 for answer*/
}
return 0;
}
答案 0 :(得分:0)
我认为你的方法不是最好的,也许如果你将二进制数存储在一个char数组中然后分析它一切都变得更容易;)。
如果我是你,我会这样做:
#include <stdio.h>
#include <math.h>
int main ()
{
char binary [20];
printf ("Input the binary number: ");
scanf ("%s", binary);
int length = 0;
while (binary [length] != '\0')
++length;
int decimal = 0;
for (int i = length - 1; i > -1; --i)
{
if (binary [i] == '1')
decimal += pow (2, length - i - 1);
}
printf ("To decimal: %d\n", decimal);
return 0;
}