gpt4 book ai didi

c - 垃圾值正在被分配

转载 作者:行者123 更新时间:2023-11-30 21:11:15 24 4
gpt4 key购买 nike

这基本上将表达式作为输入并从左到右对其进行计算。没有优先权。当我编辑变量名称时,我破坏了一些东西。它不适用于简单的表达式 x。输入示例:x+3-4*x1633331000

#include<stdio.h>
#include<math.h>

int result=0;
char op;



//This function computes the operations and returns an integer
int compute(int r, int x, char op)
{
switch (op)
{
case '+':return r+x;
break;
case '-':return r-x;
break;
case '/':return r/x;
break;
case '*':return r*x;
break;
case '^':return (int) pow((double) r,x);
break;

}
}

//This function breaks the expression into tokens and computes result in result variable
void solveExpression(char expression[],int n, int x)
{
int i;
char temp[10];
int pos=0;
int check = 0;
//int result=0;
for(i=0;i<=n;i++)
{
//store first number
if((check==0)&&(expression[i]>='0')&&(expression[i]<='9'))
{
pos=0;
temp[pos]=expression[i];
temp[pos+1] = '\0';
pos++;
check = 1;
}
//store second number
else if ((check==1)&&(expression[i]>='0')&&(expression[i]<='9'))
{
temp[pos]=expression[i];
temp[pos+1] = '\0';
pos++;

}
//check character
else
{
//if exists, store char temp[] as int op
if(pos>0)
{
//if it is first number
if (op=='\0')
result =atoi(temp);
//if it is number in the centre
else result=compute(result, atoi(temp), op);
}

//reset values
pos=0;
check = 0;

//Check for letter
if (expression[i]=='x')
{
if (op=='\0')
result=x;
else
result = compute(result,x,op);
}

//Check for operator
else if ((expression[i]=='+')
||(expression[i]=='-')
||(expression[i]=='*')
||(expression[i]=='/')
||(expression[i]=='^'))

{
op=expression[i];
}
}
}

}


int main(void)
{
int vali=0;
char expression[80] ;
int arr_value[100];
int x;

//Scan Expression
scanf("%[^\n]s", expression);

//Fill array of values until input value=1000
while(1)
{
scanf("%d", &arr_value[vali]);
if(arr_value[vali]==1000)
break;
else
vali++;
}


vali=0;
//Compute for each value
while(arr_value[vali]!=1000)
{
//Set global x value
x=arr_value[vali];
//Solve expression
//Print result
solveExpression(expression,80,x) ;
printf("\n result %d\n", result);
//Next Value
vali++;
result=0;

}
printf("\n");
}

最佳答案

每次 while 循环迭代时,全局变量 op 和 result 都需要重置。

while(arr_value[vali]!=1000)
{
//Set global x value
x=arr_value[vali];
//Solve expression
//Print result
solveExpression(expression,80,x) ;
printf("\n result %d\n", result);
//Next Value
vali++;
result=0;
op='\0'; // add this line to reset global variable
}

关于c - 垃圾值正在被分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24838942/

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