1 x 2 0 +1 x 2 1 + 1 x 2 2 + 0 x 2 3 +1 x 2 4 = 1 + 2 x (1 + 2 x (1 + 2 x (0 + 2 x 1) ))
记起b[0] = 1, b[1] = 1, b[2] = 1,b[3] = 0, b[4] = 1
/* to convert a binary representation to a decimal one*/
int dec, b[5] = {1, 1, 1, 0, 1};
dec = b[4];
for (int i = 3; i >= 0; i--)
{
dec=2 * dec + b[i]; //horner's scheme
}
cout << dec << endl;
我试图用 C 语言再次编写这段代码,但它不能正常工作:
#include<stdio.h>
int main()
{
int B[5];
int x, s, s1;
for(int i = 1;i <= 5; i++)
{
printf("Enter %d. digit of binary number", i);
scanf("%d", &B[i]);
}
s = B[5]; /*this part for reverse the array*/
B[5] = B[1];
B[1] = s;
s1 = B[4];
B[4] = B[2];
B[2] = s1;
x = B[4];
for (int i = 3; i >= 0; i--)
{
x = 2 * x + B[i];
}
printf("%d", x);
scanf("%d");
}