题解 | #计算表达式#
计算表达式
https://www.nowcoder.com/practice/7b18aa6b7cc14f8eaae6b8acdebf890b
#include <stdio.h> #include<string.h> int count(char *p,int *d){ int sum=0; while(*p>='0'&&*p<='9'){ sum=sum*10+*p-'0'; p++; *d=*d+1; } return sum; } float func(char *p,int tap){ float sum=0; while(*p>='0'&&*p<='9'){ sum=sum*10+*p-'0'; p++; } if(tap)sum=-sum; while(*p=='*'||*p=='/'){ if(*p=='*'){ int d=0; sum=sum*count(++p,&d); p+=d; } else{ int d=0; sum=sum/count(++p,&d); p+=d; } } if(*p=='+'){ tap=0; return sum+func(++p,tap); } else if(*p=='-'){ tap=1; return sum+func(++p,tap); } else { return sum; } } int main(){ char arr[50],tap; while(scanf("%s",arr)!=EOF){ char *p=arr;tap=0; printf("%.f\n",func(p,tap)); } return 0; }