當前位置:首頁 » 編程語言 » c語言混合運算

c語言混合運算

發布時間: 2023-09-15 03:48:28

c語言簡單四則混合運算代碼

四則混合運算代碼:
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
char token[61]; /*存放表達式字元串的數組*/
int n=0;
void error(void) /*報告錯誤函數*/
{
printf("ERROR!\n");
exit(1);
}
void match(char expected) /*檢查字元匹配的函數*/
{
if(token[n]==expected)
token[++n]=getchar();
else error();
}
double term(void); /*計算乘除的函數*/
double factor(void); /*處理括弧和數字的函數*/
double exp(void) /*計算加減的函數*/
{
double temp=term();
while((token[n]=='+')||(token[n]=='-'))
switch(token[n])
{
case'+':match('+');
temp+=term();
break;
case'-':match('-');
temp-=term();
break;
}
return temp;
}
double term(void)
{
double div;
double temp=factor();
while((token[n]=='*')||(token[n]=='/'))
switch(token[n])
{
case'*':match('*');
temp*=factor();
break;
case'/':match('/');
div=factor();
if(div==0) /*處理除數為零的情況*/
{
printf("The divisor is zero!\n");
exit(1);
}
temp/=div;
break;
}
return temp;
}
double factor(void)
{
double temp;
char number[61];
int i=0;
if(token[n]=='(')
{
match('(');
temp=exp();
match(')');
}
else if(isdigit(token[n])||token[n]=='.')
{
while(isdigit(token[n])||token[n]=='.') /*將字元串轉換為浮點數*/
{
number[i++]=token[n++];
token[n]=getchar();
}
number[i]='\0';
temp=atof(number);
}
else error();
return temp;
}
main()
{
double result;
FILE *data=fopen("61590_4.dat","at");
if(data==NULL)
data=fopen("61590_4.dat","wt");
if(data==NULL)
return 0;
token[n]=getchar();
result=exp();
if(token[n]=='\n')
{
token[n]='\0';
printf("%s=%g\n",token,result);
fprintf(data,"%s=%g\n",token,result);
}
else error();
fclose(data);
return 0;
getch();
}

Ⅱ 怎樣用C語言編寫一個簡單的可以進行加減乘除運算混合運算的計算器

用C語言編寫一個簡單的可以進行加減乘除運算混合運算的計算器的方法:

1、打開visual C++ 6.0-文件-新建-文件-C++ Source File;

Ⅲ c語言模擬計算器四則混合運算

//此演算法只能進行整數四則混合運算,也不支持括弧
//按下面的格式輸入表達式(末尾無=)
//10-5+4+6/2*14*8/4-5*7+2-4*6/2-10*4-6/3
#include<stdio.h>

int jisuan(int num1,char op1,int num2)
{
switch(op1)
{
case '*':
return num1*num2;
case '/':
return num1/num2;
case '+':
return num1+num2;
case '-':
return num1-num2;
}
}

int process(int num1,char op1,int num2)
{
int r,num3;
char op2;

if('\n'!=(op2=getchar()))
{
scanf("%d",&num3);
if('+'==op2 || '-'==op2)
{
num1=jisuan(num1,op1,num2);
r=process(num1,op2,num3);
}
else if('*'==op2 || '/'==op2)
{
if('/'==op1)
{
num1=jisuan(num1,op1,num2);
r=process(num1,op2,num3);
}
else
{
num2=jisuan(num2,op2,num3);
r=process(num1,op1,num2);
}
}
}
else
{
r=jisuan(num1,op1,num2);
}
return r;
}

int main()
{
int num1,num2;
char op;

printf("請輸入一個表達式:");
scanf("%d%c%d",&num1,&op,&num2);
printf("=%d\n",process(num1,op,num2));
return 0;
}

熱點內容
滑板鞋腳本視頻 發布:2025-02-02 09:48:54 瀏覽:432
群暉怎麼玩安卓模擬器 發布:2025-02-02 09:45:23 瀏覽:557
三星安卓12彩蛋怎麼玩 發布:2025-02-02 09:44:39 瀏覽:743
電腦顯示連接伺服器錯誤 發布:2025-02-02 09:24:10 瀏覽:536
瑞芯微開發板編譯 發布:2025-02-02 09:22:54 瀏覽:146
linux虛擬機用gcc編譯時顯示錯誤 發布:2025-02-02 09:14:01 瀏覽:232
java駝峰 發布:2025-02-02 09:13:26 瀏覽:651
魔獸腳本怎麼用 發布:2025-02-02 09:10:28 瀏覽:532
linuxadobe 發布:2025-02-02 09:09:43 瀏覽:212
sql2000資料庫連接 發布:2025-02-02 09:09:43 瀏覽:726