⑴ 怎么用C++编译一个简单的计算器
我借鉴了别人的某计算器,因为你没有说多简易...我就找了个差不多的...
/*
程序名称:表达式计算器
编译环境:Microsoft Visual C++ 6.0
作者:吉林大学 计算机科学与技术学院 2006 罗泗勇
时间:200801
*/
/*
说明:
采用树形结构处理表达式,按优先级运算结果,一个加,减,乘,除或数值为一个节点
优先级如下:
函数:4
括号:3
乘除:2
加减:1
*/
#include <windows.h>
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
using namespace std;
const char NUM[]={'0','1','2','3','4','5','6','7','8','9','.'};
const char OPERATION[]={'+','-','*','/'};
const double PI=3.14159265358979;
const double EE=2.71828182818281;
class Fun //处理系统数学函数的类
{
public:
Fun(string o,int t,double l=0.0,double r=0.0):op(o),type(t),lvalue(l),rvalue(r){}
static string FUN[];
double calc();
private:
int type; //666 0 1 sin90 2 3! 3 3C2
string op; //函数类型
double lvalue; //函数左边的值
double rvalue; //函数右边的值
static int FunNum;
};
int Fun::FunNum=8;
string Fun::FUN[]={"!","sin","cos","tan","log","ln","C","A","^"};
/*
函数说明:
1:log是以10为底的工程对数
2:ln 是以e为底的自然对数
3:C 计算组合数 输入规则 如计算 3取2的组合 输入表达式 3C2
4:A 计算排列数 输入规则 如计算 3取2的排列 输入表达式 3A2
5:! 计算阶乘
6:^ x的y次方 输入 x^y
*/
int factorial(int n) //阶乘函数
{
int i,s=1;
for(i=1;i<=n;i++)
s*=i;
return s;
}
int C(int a,int b)
{
return factorial(a)/(factorial(b)*factorial(a-b));
}
int A(int a,int b)
{
return factorial(a)/factorial(b);
}
double Fun::calc() //计算系统函数的值
{
if(type==0)
return lvalue;
else
{
if(op=="!")
return factorial(lvalue);
if(op=="sin")
return sin(rvalue/180*PI);
if(op=="cos")
return cos(rvalue/180*PI);
if(op=="tan")
return tan(rvalue/180*PI);
if(op=="log")
return log10(rvalue);
if(op=="ln")
return log10(rvalue)/log10(EE);
if(op=="C")
return C(lvalue,rvalue);
if(op=="A")
return A(lvalue,rvalue);
if(op=="^")
return pow(lvalue,rvalue);
else
{
string err="暂时没有函数"+op;
MessageBox(NULL,err.c_str(),"错误",MB_OK);
return 0;
}
}
}
struct Unit //双向链表保存运算单元
{
Unit(int p,char o,string c,double v,int t,Unit * pr=NULL,Unit * n=NULL)
:PRI(p),Operation(o),Code(c),value(v),Type(t),Pre(pr),Next(n){}
int PRI; //优先级
char Operation; //操作符
string Code; //原始代码
double value; //数据
int Type; //类型 操作符0 数据1 函数2
Unit * Pre; //构成双向链表
Unit * Next;
};
class Node //表达式树状结构的节点
{
public:
Node(char o,int p,int e=1,double v=0,Node * ph=NULL,Node * pl=NULL,Node * pr=NULL)
:Operation(o),PRI(p),Expression(e),value(v),Head(ph),Left(pl),Right(pr){}
Node * Head; //节点的根,左树枝,右树枝
Node * Left;
Node * Right;
double GetValue();
char GetOperation() const {return Operation;}
int GetPri() const {return PRI;}
int IsExp() const {return Expression;}
private:
char Operation; //操作符
int PRI; //优先级
int Expression; //记录该节点是否是表达式0 1
double value; //该节点的值
};
double Node::GetValue() //运算该节点的值
{
if(IsExp()) //该节点的值还未算出来
{
double lvalue,rvalue;
lvalue=Left->GetValue();
rvalue=Right->GetValue();
Expression=0;
char op=GetOperation();
switch(op)
{
case '+':
return lvalue+rvalue;
case '-':
return lvalue-rvalue;
case '*':
return lvalue*rvalue;
case '/':
return lvalue/rvalue;
default:
return 0;
}
}
else
return value;
}
bool Isnum(char c)
{
for(int i=0;i<sizeof(NUM);i++)
{
if(c==NUM[i])
return true;
}
return false;
}
bool Isoperation(char c)
{
for(int i=0;i<sizeof(OPERATION);i++)
{
if(c==OPERATION[i])
return true;
}
return false;
}
Unit * Analyse(string exp) //分析表达式并生成链表
{
int pri=0; //当前优先级
int stat=-1; //当前的读入状态 括号 0 数据 1 运算符 2
Unit * head=NULL,* p=NULL;
int i=0,explen;
explen=exp.size();
for(i=0;i<explen;i++)
{
char c=exp.at(i);
if(c=='(')
{
pri+=3;
stat=0;
}
else if(c==')')
{
pri-=3;
stat=0;
}
else if(Isoperation(c)) //操作符不会出现在表达式开头
{
Unit * temp=p;
int add_pri; //自身增加的优先级
if(c=='+' || c=='-')
add_pri=1;
else
add_pri=2;
p->Next=new Unit(pri+add_pri,c," ",0,0);
p=p->Next;
p->Pre=temp;
}
else //其他的当做函数处理
{
string function="";
while(i<explen && (c=exp.at(i),! Isoperation(c)) && c!=')')
{
function+=c;
i++;
}
i--;
if(head==NULL)
{
p=new Unit(pri,' ',function,0,2);
head=p;
}
else
{
Unit * temp=p;
p->Next=new Unit(pri,' ',function,0,2);
p=p->Next;
p->Pre=temp;
}
}
}
return head;
}
Unit * Calc(Unit * head) //计算双向链表基本单元的值
{
Unit * p=head;
while(p!=NULL)
{
if(p->Type!=0) //非操作符
{
string temp=p->Code;
string op;
double lvalue=0,rvalue=0;
int l_point=0,r_point=0;
int i=0,type=0;
char ch;
while(i<temp.size() && (ch=temp.at(i),Isnum(ch)))
{
if(ch=='.')
{
l_point++;
i++;
continue;
}
if(! l_point)
lvalue*=10;
lvalue+=(ch-'0')*pow(10,-l_point);
i++;
if(l_point)
l_point++;
}
while(i<temp.size() && (ch=temp.at(i),! Isnum(ch)))
{
op+=ch;
type=1;
i++;
}
while(i<temp.size() && (ch=temp.at(i),Isnum(ch)))
{
if(ch=='.')
{
r_point++;
i++;
continue;
}
if(! r_point)
rvalue*=10;
rvalue+=(ch-'0')*pow(10,-r_point);
i++;
if(r_point)
r_point++;
}
Fun * f=new Fun(op,type,lvalue,rvalue);
p->value=f->calc();
}
p=p->Next;
}
return head;
}
Node * Tree(Unit * head) //生成表达式树
{
Node * root=NULL,* proot=NULL,* pbranch=NULL;
Unit * p=head;
int now_pri; //当前优先级
bool hadop=false;
while(p!=NULL)
{
if(p->Type==0) //如果是一个操作符
{
hadop=true;
if(root==NULL)
{
proot=new Node(p->Operation,p->PRI,1);
root=proot;
pbranch=root;
now_pri=p->PRI;
proot->Left=new Node(' ',0,0,p->Pre->value);
proot->Right=new Node(' ',0,0,p->Next->value);
}
else
{
if(p->PRI<=now_pri) //优先级低于当前优先级,树根方向 //最初写的 if(p->PRI<now_pri),9/3/3=9,错的
{
proot=new Node(p->Operation,p->PRI,1); //新的树根
proot->Left=root; //根的变换
proot->Right=new Node(' ',0,0,p->Next->value);
root=proot;
pbranch=proot; //右树枝的变换
//pbranch->Right=new Node(' ',0,0,p->Pre->value); //树枝右边取值
}
else
{
Node * temp;
temp=new Node(p->Operation,p->PRI,1);
pbranch->Right=temp;
temp->Head=pbranch;
pbranch=pbranch->Right;
pbranch->Left=new Node(' ',0,0,p->Pre->value);
pbranch->Right=new Node(' ',0,0,p->Next->value);
}
now_pri=p->PRI;
}
}
p=p->Next;
}
if(! hadop)
root=new Node(' ',0,0,head->value);
return root;
}
int main()
{
string exp;
//ifstream infile("test.txt",ios::in);
while(! getline(cin,exp).eof())
{
if(exp=="")
continue;
Unit * h=Analyse(exp);
h=Calc(h);
Node * root=Tree(h);
cout<<exp<<"="<<root->GetValue()<<endl;
}
return 0;
}
⑵ 用简单c语言编写计算器
#include"stdio.h"
/*预处理命令*/
void
main()
/*主函数*/
{
double
a,b;
/*双精度实型变量说明*/
char
c,d;
/*变量说明*/
do
/*循环体*/
{
printf("input
a
(-*/)b\n");
/*输入提示*/
scanf("%lf%c%lf",&a,&c,&b);
/*输入算术表达式*/
if(c=='
')
/*判断
*/
printf("=%0.2f",a
b);
/*输出a
b的值*/
else
if(c=='-')
/*判断-*/
printf("=%0.2f",a-b);
/*输出a-b的值*/
else
if(c=='*')
/*判断**/
printf("=%0.2f",a*b);
/*输出a*b的值*/
else
if(c=='/')
/*判断/*/
printf("=%0.3f",a/b);
/*输出a/b*/
else
/*不满足以上条件*/
printf("error");
/*输出错误*/
printf("\n\ninput\n");
/*输入\n*/
scanf("%c",&d);
/*输入符号给d*/
}
/*循环体结束*/
while(d=='\n');
/*循环条件语句*/
}
⑶ 一个计算器怎么用C语言编译
#include<stdio.h>
int main() {
double num1 = 0; //输入1
double num2 = 0; //输入2
char ch; //操作
double ret = 0; //结果 printf( "输入第一个数:" );
scanf( "%lf", &num1 );
printf( "输入第二个数:" );
scanf( "%lf", &num2 );
printf( "操作[+ - * /]:" );
getchar();
scanf( "%c", &ch ); switch( ch ) {
case '+':
ret = num1 + num2;
break;
case '-':
ret = num1 - num2;
break;
case '*':
ret = num1 * num2;
break;
case '/':
ret = num1 / num2;
break;
default:
break;
}
printf( "结果:%.2lf\n", ret ); return 0;
}
⑷ 怎样用C语言编写一个简单的可以进行加减乘除运算混合运算的计算器
用C语言编写一个简单的可以进行加减乘除运算混合运算的计算器的方法:
1、打开visual C++ 6.0-文件-新建-文件-C++ Source File;
⑸ 如何用C语言编写一个科学计算器
用栈 就可以办到了。。。这个很详细的, lz 随便输入一个表达式,中间的计算过程全部输出了,lz试两个 就知道怎么回事了。 #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSIZE 4000;
typedef struct
{
char data[10];
int top;//头地址
int base;//基地址
int length;//长度
}Stack;
void init(Stack *st)//初始化栈
{
st->base=0;
st->top=0;
st->length=0;
}
int isEmpty(Stack *st)
{
int n=0,top,base;
top =st->top;
base =st->base;
if(top==base)
{
return 1;
}
return n;
}
int isFull(Stack *st)
{
int n=0,top,base;
top =st->top;
if(top>=4000)
{
return 1;
}
return n;
}
char getTop(Stack *st)// 返回top值,不改变栈的结构
{
char n;
if(isEmpty(st))
{
printf("栈为空\n");
return 0;
}
int positon= st->top-1;
n= st->data[positon];//取出数据;
return n;
}
char pop(Stack *st)// 出栈,返回
{
char n;
if(isEmpty(st))
{
printf("栈为空\n");
return 0;
}
int positon= st->top-1;
n= st->data[positon];//取出数据;
st->top--;
st->length--;
st->data[positon]='\0';//消除数据
return n;
}
void push(char n,Stack *st)//入栈
{
int positon ;
if(isFull(st))
{
printf("栈满\n");
}
else
{
positon= st->top;//获取位置
st->data[positon]=n;//存入数据
st->top++;//改变位置
}
}
void show(Stack *m1)//输出栈中的数据
{
int top,base;
top=m1->top;
base=m1->base;
while(top>base)
{
printf("%c,",m1->data[--top]);
}
printf("\n");
}
int isOperate(char temp)//是否是操作符
{
if(temp=='+'||temp=='-'||temp=='*'||temp=='/'||temp=='('||temp==')'||temp=='#')
{
return 1;
}
return 0;
}
int isValue(char temp)//是否是数值
{
if(temp>='0'&&temp<='9')//
{
return 1;
}
else
{
return 0;
}
}
int isAvail(char temp)//是否有效字符
{
if(isOperate(temp)||isValue(temp))//如果temp既不是操作符和数值的话,则它是非法的
{
return 1;
}
return 0;
}
int detect(char temp)//搜索矩阵位置
{
int i=0;
char oper[7]={'+','-','*','/','(',')','#'};
for(i=0;i<7;i++)
{
if(temp==oper[i])
{
return i;
}
}
}
char Priority(char temp,char optr)//判断优先级
{
/**//*
+ - * / ( ) #
1 2 3 4 5 6 7
+ 1 < < < < > > >
- 2 < < < < > > >
* 3 > > < < > > >
/ 4 > > < < > > >
( 5 > > > > > = 0
) 6 < < < < = 0 >
# 7 < < < < > 0 =
*/
int row ,col;
char priority[7][7]={/**//* + - * / ( ) # */
{'<','<','<','<','>','>','>'},
{'<','<','<','<','>','>','>'},
{'>','>','<','<','>','>','>'},
{'>','>','<','<','>','>','>'},
{'>','>','>','>','>','=','>'},
{'<','<','<','<','=','0','>'},
{'<','<','<','<','>','<','='},
};
row = detect(temp);//找出对应的矩阵下标;
col = detect(optr);
// printf("%d,%d",row,col);
//优先级存储在一个7x7的矩阵中,对应关系上图;
return priority[row][col];
}
char evaluate(int a,int b,char oper)
{
switch(oper)
{
case '+': return a+b+'0';
case '-': return a-b+'0';
case '*': return a*b+'0';
case '/': return a/b+'0';
default : return 0+'0';
}
}
int calculateExpress(char *express)//计算表达式
{
int result=0;
int a,b;
// char oper,result;
Stack OPTR,OPND;//OPTR存储操作符,OPND操作数值
init(&OPTR);
init(&OPND);
push('#',&OPTR);//默认第一个位'#'
////////////////////-算法-////////////////////////////
while(*express!='\0')
{
char temp;
temp= *(express);
printf("---------------------------------\n");
printf("当前的符号为%c\n",temp);
if(isAvail(temp))//是否是有效字符
{
if(isOperate(temp) )//输入的是操作符
{
char oper,result;
char optr = getTop(&OPTR);//栈中top位的操作符
printf("栈顶操作符位:%c\n",optr);
char prior = Priority(temp,optr);//判断优先级
switch(prior)
{
case '>':
push(temp,&OPTR);
printf("将符号位%c入栈\n",temp);
express++;
break;
case '<':
//int a,b;
//char oper,result;
a=pop(&OPND)-'0';//存在栈中的都是char字符
b=pop(&OPND)-'0';
oper=pop(&OPTR);
result=evaluate(b,a,oper);//出栈一个操作符,计算结果
//printf("%d",result-'0');
push(result,&OPND);//结果入OPND
printf("%d%c%d结果为:%d\n",b,oper,a,result-'0');
break;
case '=':
//消除括号
pop(&OPTR);
printf("消除括号\n");
express++;
break;
}
}
if(isValue(temp))//输入的是数值
{
push(temp,&OPND);//将数值位入栈;
express++;
printf("将数值%c压入栈\n",temp);
//show(&OPND);
}
}
else //表达式中有非法字符
{
printf("表达式中有非法字符\n");
exit(-1);//退出程序
}
}
// show(&OPND);
// show(&OPTR);
return getTop(&OPND)-'0';
}
void inputExpress(char *express)//输入表达式
{
int length=0;
printf("请输入一个表达式:");
scanf("%s",express);
int len =strlen(express);
express[len]='#';//表达式最后一位默认为'#';
express[len+1]='\0';
}
void output(char *express,int result)//输出表达式
{
int i=0;
printf("----------------------------------------\n表达式:");
while(express[i]!='#')
{
printf("%c",express[i]);
i++;
}
printf("=%d\n",result);
}
int main()
{
char express[100];//表达式
int result =0;
inputExpress(express);//输入表达式
result = calculateExpress(express);//计算表达式;
output(express,result); //输出表达式
//、、、、、、、、、、、、、测试优先级。
/**//*
char m='7' ;
m=Priority('+','*');
printf("优先级为%c",m);
int m=evaluate(5,6,'m');
printf("%d",m);
*/
return 0;
}
⑹ 怎样用c语言编写一个简的计算器程序
/* 2013年12月23日 12:43:46 目的:计算器的实现 */ # include <stdio.h> # include <ctype.h> # include <math.h> char get_choice(void); //获取用户输入的选项,并建立目 char get_first(void); //获取用户输入的选项,并剔除错误输入 float get_int(void); //获取用户输入的计算值 float add(void); //定义加法函数 float subtraction(void); //定义减法函数 float multiplication(void); //定义乘法函数 float division(void); //定义除法函数 float extract(void); //定义开方函数 float square(void); //定义平方函数 float cube(void); //定义立方函数 int count = 0; int main(void) { char choice; printf("***欢迎使用由小钱制作的计算器***\n"); choice = get_choice(); while(choice != 'q') { switch(choice) { case 'a': add(); break; case 'b': subtraction(); break; case 'c': multiplication(); break; case 'd': division(); break; case 'e': extract(); break; case 'f': square(); break; case 'g': cube(); break; default : printf("您输入有误,请重新输入:"); break; } fflush(stdin); choice = get_choice(); } printf("bye"); return 0; } //获取用户输入的选项,并建立目录 char get_choice(void) { char ch; int a = 0; //建立目录 printf("\n--------------------------------\n"); printf("a. 加法\t\t\tb. 减法\nc. 乘法\t\t\td. 除法\n"); printf("e. 开方\t\t\tf. 平方\ng. 立方\t\t\tq. 退出\n"); printf("--------------------------------\n"); printf("请输入你的选项:"); ch = get_first(); while(ch == ' ' || ch == '\n' || ch == '\t') ch = get_first(); //判断用户输入的选项是否有误 while((ch<'a' || ch>'g') && ch !='q') { putchar(ch); printf(" 你输入的选项有误,请重新输入:"); ch = get_first(); } return ch; } //获取用户输入的选项,并剔除错误输入 char get_first(void) { char ch; ch = getchar(); //剔除由用户输入选项时产生的换行符 while(ch == '\n') { ch = getchar(); } return ch; } //获取用户输入的计算值 float get_int(void) { float input; char ch; int a; if(count == 0) printf("亲!请输入数值:"); if(count == 1) printf("亲!请输入第一个数值:"); if(count == 2) printf("亲!请输入第二个数值:"); a = scanf("%f", &input); //判断用户的输入是否为一个数值 while(a != 1) { //剔除用户输入错误的字符 while((ch = getchar()) != '\n') { putchar(ch); printf(" 不是一个数值,请输入例如3、111.2、或者-1"); a = scanf("%f", &input); } } return input; } //定义加法函数 float add(void) { float i, j, sum; count = 0; count = count+1; i = get_int(); count = count+1; j = get_int(); sum = i + j; printf("%.2f + %.2f = %.2f\n", i, j, sum); return sum; } //定义减法函数 float subtraction(void) { float i, j, sum; count = 0; count = count+1; i = get_int(); count = count+1; j = get_int(); sum = i - j; printf("%.2f - %.2f = %.2f\n", i, j, sum); return sum; } //定义乘法函数 float multiplication(void) { float i, j, sum; count = 0; count = count+1; i = get_int(); count = count+1; j = get_int(); sum = i * j; printf("%.2f * %.2f = %.2f\n", i, j, sum); return sum; } //定义除法函数 float division(void) { float i, j, sum; count = 0; count = count+1; i = get_int(); count = count+1; j = get_int(); //判断除数是否为0 while(j == 0) { printf("除数不能为0\n请重新输入!!!\n"); j = get_int(); } sum = i / j; printf("%.2f / %.2f = %.2f\n", i, j, sum); return sum; } //定义开方函数 float extract(void) { float i, sum; count = 0; i = get_int(); //判断开方数是否小于0,如果小于0,则让用户重新输入 while(i < 0) { printf("请输入大于0的数值\n"); i = get_int(); } sum = sqrt(i); printf("%.2f的开方等于%.2f\n", i, sum); return sum; } //定义平方函数 float square(void) { float i, sum; count = 0; i = get_int(); sum = i * i; printf("%.2f的平方等于%.2f\n", i, sum); return sum; } //定义立方函数 float cube(void) { float i, sum; count = 0; i = get_int(); sum = i * i * i; printf("%f的立方等于%.3f\n", i, sum); return sum; }
⑺ 如何使用C语言做一个简单的计算器
#include<stdio.h>
main()
{
floata[100];
inti,j;
charb[100];
while(1)
{
for(i=0;i<=99;i++)
{
scanf("%f%c",&a[i],&b[i]);
if(b[i]=='=')break;
}
for(j=0;j<=i;j++)
{
switch(b[j])
{
case'+':a[j+1]=a[j]+a[j+1];break;
case'-':a[j+1]=a[j]-a[j+1];break;
case'*':a[j+1]=a[j]*a[j+1];break;
case'/':a[j+1]=a[j]/a[j+1];break;
case'=':printf("%f ",a[j]);
}
}
}
getch();
}
说明:输入格式为"10.2+1.8/3=",记住
最后一定要输入"=",再敲回车键,在
TC中运行要加"getch();"以显示结果。
回复:我用的是VC++6.0,调试和运行都
无异常,是不是你最后忘记加等号了,
还是输入数字之后加了空格,为了输入
的方便,我没有设计加空格,直接输入
就可以了,比如输入“3+4-5/2=”,输
出“1.000000",如还有问题可加我。
⑻ 怎么用c语言编写计算器啊
堆栈是数据结构的内容,对初学者来说是很难的。可以不用这个,我写一个吧
#include"stdio.h"
void main(){
int a, b;
int s;
printf("输入2个数");
scanf("%d",&a);
scanf("%d",&b);
char c;
printf("输入计算符号");
scanf("%c",&c);
switch(c)
case '+':s=a+b;
case '-':s=a-b;
case '*':s=a*b;
case '/':s=a/b;
printf("计算结果是%d",s);}
//这个计算器比较简单。
⑼ 用c语言编写一个简单计算器程序
#include<stdio.h>//计算器
voidmenu()//自定义的菜单界面
{
printf("--------------------\n");
printf("请输入你的选择\n");
printf("1.+\n");
printf("2.-\n");
printf("3.*\n");
printf("4./\n");
printf("--------------------\n");
}
intmain()
{
inti=0;
intj=0;
intnum=0;//计算结果存放在nun
intselect=0;//选择的选项存放在select
do//do-while先执行再判断循环条件,即可实现重复计算功能
{
menu();//打印出菜单界面
scanf("%d",&select);//输入你的选项
printf("请输入计算值:");
scanf("%d%d",&i,&j);//输入要计算的数值
switch(select)
{
case1:
printf("%d+%d=%d\n",i,j,num=i+j);//实现加法功能
break;
case2:
printf("%d-%d=%d\n",i,j,num=i-j);//实现减法功能
break;
case3:
printf("%d*%d=%d\n",i,j,num=i*j);//实现乘法功能
break;
case4:
printf("%d-%d=%d\n",i,j,num=i/j);//实现除法功能
break;
default:
printf("输入有误重新选择");
break;
}
}while(select);
return0;
}
运行结果:
return表示把程序流程从被调函数转向主调函数并把表达式的值带回主调函数,实现函数值的返回,返回时可附带一个返回值,由return后面的参数指定。
return通常是必要的,因为函数调用的时候计算结果通常是通过返回值带出的。如果函数执行不需要返回计算结果,也经常需要返回一个状态码来表示函数执行的顺利与否(-1和0就是最常用的状态码),主调函数可以通过返回值判断被调函数的执行情况。
⑽ 如何用C程序编写一个计算器
1
首先,得从网上下载并安装c++,然后从桌面找到并打开它。