用c語言編寫四則運算
1234567891011121314151617# include <stdio.h>int main(void){ int a,b,s; char c; scanf("%d%c%d",&a,&c,&b); switch(c) { case '+':s=a+b;break; case '-':s=a-b;break; case '*':s=a*b;break; case '/':s=a/b;break; default:return -1; } printf("%d",s); return 0;}
如果還要判斷除數為0的情況 再添個if即可
Ⅱ 用c語言編四則運算
用C++寫的,用C的話,函數方面很繁瑣...
實現不止是整數,小數也可以,但算式中不要有負數,結果中可以有.
2000字不夠用,分兩部分,前一部分一些全局變數和類的申明:
#include
<iostream.h>
#include
<string.h>
#include
<stdlib.h>
#include
<math.h>
#define
MAX
100
//定義運算優先順序數組,1表示優先,0表示相等,-1表示非優先,2表示表達式有誤
int
com_value[9][9]=
{
1,1,-1,-1,-1,1,1,1,2,
1,1,-1,-1,-1,1,1,1,2,
1,1,1,1,-1,-1,1,1,2,
1,1,1,1,-1,-1,1,1,2,
1,1,1,1,2,-1,1,1,2,
-1,-1,-1,-1,-1,-1,0,2,2,
1,1,1,1,1,2,1,1,2,
-1,-1,-1,-1,-1,-1,2,0,2,
2,2,2,2,2,2,2,2,2
};
//堆棧類模板
template
<class
type>
class
stack
{
public:
stack(){top=new
type[MAX];};
~stack(){};
type
*top;
public:
void
push(type
e){*top=e;top++;}
type
pop(){top--;return*top;}
type
GetTop(){return
*(top-1);}
int
GetTopValue(type
&e)
{
if(e=='+')return
0;else
if(e=='-')return
1;
else
if(e=='*')return
2;else
if(e=='/')return
3;
else
if(e=='^')return
4;else
if(e=='(')return
5;
else
if(e==')')return
6;else
if(e=='=')return
7;
else
return
8;
}
int
GetTopValue()
{
type
temp=GetTop();
if(temp=='+')return
0;else
if(temp=='-')return
1;
else
if(temp=='*')return
2;else
if(temp=='/')return
3;
else
if(temp=='^')return
4;else
if(temp=='(')return
5;
else
if(temp==')')return
6;else
if(temp=='=')return
7;
else
return
8;
}
type
calculate(char
s)
{
type
b=pop(),a=pop();
if(s=='+')return
a+b;
if(s=='-')return
a-b;
if(s=='*')return
a*b;
if(s=='/')return
a/b;
if(s=='^')return
pow(a,b);
}
};
Ⅲ 用簡單的C語言實現帶括弧的四則運算
#include<stdio.h> /*庫文件包含*/
#include<string.h> /*用於字元串操作*/
#include<stdlib.h> /*用於exit函數*/
/**************************************************************************
int check(char *c)
輸入參數:
char *c: 輸入的字元串
返回參數:
0:字元串中有不符合規定的字元
1: 字元串字元符合規定,沒有不符合規定的字元.
功能:
檢查字元串中有否除了 0-9, +,-,*,/,(,),之外的其他字元,
如果有,則返回0, 表示出現錯誤。
若沒有,則返回1,表式字元串符合規定。
**************************************************************************/
int check(char *c)
{
int k=0;
while(*c!='