gpt4 book ai didi

c - 计算以字符串形式给出的算术表达式

转载 作者:行者123 更新时间:2023-11-30 19:20:40 27 4
gpt4 key购买 nike

我正在开发一个项目,需要计算以字符串形式给出的算术表达式的值。

这就是我选择使用的方式,即运行字符串直到符号相乘。在此期间,我保留乘法字符串之前的数字。如果这些数字之前有符号,我会重置字符串。最后,当我计算乘号时,我检查接下来会发生什么并将其保存到另一个字符串中。最后我计算一下结果。依此类推,直到我解决了这个练习(还有其他函数可以解决剩余的方程)。

我的问题是:乘号之前的数字没有重置,除了乘号之后的数字没有保存在额外的字符串中之外,这还会产生问题。

找到乘号并计算它的函数 -

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
char str[10] = "3+1-4*6-7";
char str1[10];
char str2[10];
int i, p = 0, k = 0;

for(i = 0; i < 10; i++) {
str1[k] = str[i];
k++;
if((str[k] == '-') | '+' | '/') {
str1[0] = 0;
}
else if(str1[k] == '*') {
while((str[i] != '-') | '+' | '*' | '/') {
str2[p] = str[i];
p++;
i++;
}
}
}
printf("%s--%s\n", str1, str2);
}

感谢任何能帮我解决问题的人或者可以推荐其他方法来解决它。

最佳答案

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct exp {
char op;
char *term;
struct exp *left;
struct exp *right;
} Exp;

Exp *make_exp2(char *str){
if(!str || !*str) return NULL;//*str == '\0' is format error.
char *mul = strrchr(str, '*');
char *div = strrchr(str, '/');
Exp *node = malloc(sizeof(*node));
if(mul == NULL && div == NULL){
node->op = '\0';
node->term = str;
node->left = node->right = NULL;
return node;
}
char *op;
op = mul < div ? div : mul;
node->op = *op;
*op = '\0';
node->left = make_exp2(str );
node->right = make_exp2(op+1);
return node;
}

Exp *make_exp(char *str){
if(!str || !*str) return NULL;//*str == '\0' is format error.
char *minus = strrchr(str, '-');
char *plus = strrchr(str, '+');
if(minus == NULL && plus == NULL)
return make_exp2(str);
char *op;
Exp *node = malloc(sizeof(*node));
op = minus < plus ? plus : minus;
node->op = *op;
*op = '\0';
node->left = make_exp(str );
node->right = make_exp(op+1);
return node;
}

#ifdef DEBUG

void print(Exp *exp, int level){
int i;
if(exp->op){
for(i=0;i<level;++i)
printf(" ");
printf("%c\n", exp->op);
for(i=0;i<level;++i)
printf(" ");
print(exp->right, level+1);
printf("\n");
for(i=0;i<level;++i)
printf(" ");
print(exp->left, level+1);
printf("\n");
} else {
for(i=0;i<level;++i)
printf(" ");
printf("%s\n", exp->term);
}
}

#endif

int main(void) {
char str[] = "3+1-4*6-7";
Exp *exp = make_exp(str);

#ifdef DEBUG
print(exp, 0);
#endif
//release exp
return 0;
}

关于c - 计算以字符串形式给出的算术表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21797584/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com