将二进制转换为十进制
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct mystack
{
int *top;
int *base;
};
//栈的结构
int main()
{
mystack stack;
stack.top = (int *)malloc(2000*sizeof(int)); //栈顶指针 = (强制类型转换)申请内存(2000个整形大小)
stack.base = stack.top; //初始化栈,栈顶 = 栈底
char c; //输入的二进制数字按字符型一个一个入栈
scanf("%c", &c);
while(c!='\n') //当输入不为回车时,压入栈
{
*stack.top = c - 48;
stack.top++;
scanf("%c", &c);
}
int i,sum = 0; //结果保存在sum里
int lenth = stack.top - stack.base; //栈的存储的数据个数
for(i = 0; i < lenth; i++)
{
stack.top--;
sum += *stack.top * pow(2, i); //按公式从最后一个二进制数开始计算
}
printf("%d ", sum);
return 0;
}
欢迎来到我的IT 博客http://www.nightsong.cc