标签:span set str bsp sizeof ram 计算 ring include
注:表达式中数字均为正数
思路:遍历字符串参数,逐个拷贝字符直到遇见运算符,记录运算符和拷贝好的字符串;字符串结束只拷贝字符。
代码如下:
#include<stdio.h> #include<string.h> #include<stdlib.h> int analysis(char *expression) { int i=0,j=0,n=0,m=0,num=0,sum=0; int param_len=strlen(expression); char *p=expression; char strnum[1024]; char oper[1024]; int splnum[1024]; memset(strnum, 0x00, 1024); memset(oper, 0x00, 1024); for(i=0; i<param_len; i++) { if(p[i] != ‘\0‘) { if(i == param_len - 1) { strnum[n] = p[i]; num = atoi(strnum); splnum[m] = num; m++; break; } if(p[i] == ‘-‘ || p[i] == ‘+‘) { n = 0; num = atoi(strnum); splnum[m] = num; oper[m] = p[i]; m++; memset(strnum, 0x00, strlen(strnum)*sizeof(char)); } else { strnum[n] = p[i]; n++; } } else { break; } } sum=splnum[0]; for(j=0; j<m; j++) { switch(oper[j]) { case ‘+‘: sum += splnum[j+1]; break; case ‘-‘: sum -= splnum[j+1]; break; default: break; } } return sum; } int main(){ int a=analysis("100+200-1"); printf("%d\n", a); }
运行结果:
计算表达式的值并输出,表达式由若干个数字和运算符(只包含加号和减号)构成
标签:span set str bsp sizeof ram 计算 ring include
原文地址:https://www.cnblogs.com/yinguojin/p/12907730.html