C语言实现一个简单的计算器
来源:互联网 发布:全国省市区数据库 编辑:程序博客网 时间:2024/04/25 16:38
#include<stdio.h>
#include<stdlib.h>
#define N 100
char stack1[N];
char stack2[N];
int top = -1;
char pop(char *stack)
{
char tmp;
if(top == -1)
{
printf("该栈为空!\n");
}
else
{
tmp = stack[top];
top--;
}
return tmp;
}
void push(char *stack,char data)
{
if(top == N-1)
{
printf("该栈已满!\n");
}
else
{
top++;
stack[top] = data;
}
}
char *topostfix(char *expstr)
{
char *postfix = (char *)malloc(sizeof(char));
int i = 0;
int j = 0;
int tmp;
while(expstr[i] != '\0')
{
switch(expstr[i])
{
case '+':
case '-':
while(top != -1 && stack1[top] != '(')
{
postfix[j++] = pop(stack1);
}
push(stack1,expstr[i++]);
break;
case '*':
case '/':
while(top != -1 && (stack1[top] == '*' || stack1[top] == '/'))
{
postfix[j++] = pop(stack1);
}
push(stack1,expstr[i++]);
break;
case '(':
push(stack1,expstr[i++]);
break;
case ')':
tmp = pop(stack1);
while(top != -1 && tmp != '(')
{
postfix[j++] = tmp;
tmp = pop(stack1);
}
i++;
break;
default :
while(expstr[i] >= '0' && expstr[i] <= '9'
&& expstr[i] != '\0')
{
postfix[j++] = expstr[i++];
}
postfix[j++] = ' ';
break;
}
}
while(top != -1)
{
postfix[j++] = pop(stack1);
}
postfix[j] = '\0';
return postfix;
}
int operation(char *postfix)
{
int i = 0;
int result;
while(postfix[i] != '\0')
{
if(postfix[i] >= '0' && postfix[i] <= '9')
{
result = 0;
while(postfix[i] != ' ')
{
result = result * 10 + (postfix[i] - '0');
i++;
}
i++;
push(stack2,result);
}
else
{
if(postfix[i] != ' ')
{
int y = pop(stack2);
int x = pop(stack2);
switch(postfix[i])
{
case '+':
result = x + y;
break;
case '-':
result = x - y;
break;
case '*':
result = x * y;
break;
case '/':
result = x / y;
break;
}
push(stack2,result);
}
i++;
}
}
return result;
}
int main()
{
int result;
char expstr[N];
char *postfix = (char *)malloc(sizeof(char));
printf("请输入表达式:");
gets(expstr);
printf("你输入的表达式为:");
puts(expstr);
postfix = topostfix(expstr);
printf("你输入的表达式的后缀表达式为:");
puts(postfix);
result = operation(postfix);
printf("%s=%d\n",expstr,result);
return 0;
}
本来想实现浮点型的,myatof是写好了,但还有很多困难~~~~遂不大想写了~~
这个计算器只有+,-,*,/,()~~~~
给点点你们改的空间,将结果能输出为浮点型~~~~~
提示:强制类型转换~~~~
- C语言实现一个简单的计算器
- 用C语言实现一个简单的计算器代码
- 一个简单的计算器(C语言)
- 【c语言】一个简单的计算器
- C语言-一个简单的计算器。。。。。
- 一个计算器的C语言实现
- C语言模块化开发简单实例——实现一个计算器的加减乘除
- C语言写的一个简单的计算器
- C语言不用scanf函数的一个简单的计算器
- 用C语言编写一个简单的“+”“”-“”*“/”计算器
- 用C语言编写一个“+”“-”“*”“/”简单的计算器
- C语言实现的简单的逆波兰计算器
- 用C语言设计一个简单计算器
- 一个简单的计算器的实现(C++)
- 一个简单的计算器的实现(C++)
- 实现一个简单的计算器
- C语言 实现四则运算简单计算器
- 用C语言实现一个计算器
- 简介C++ 异常处理
- AddType requires at least two arguments, a mime type followed by one or more file extensions
- 电力线适配器
- tftp
- 创建cocoa链接库并进行单元测试
- C语言实现一个简单的计算器
- Extjs学习 三种方式提交form表单
- xmu 1069.圣斗士黄金十二宫(五)卡妙的提问
- 实作一个二维条码生成的Chrome插件
- 用wxSlider创建滑块控件
- HDU 2234 无题I IDA*搜索
- Linux与Android的关系
- 编程之美3.3——计算字符串的相似度
- cocos2d学习笔记(五)CCMenu与CocosDenshion