gpt4 book ai didi

c - 用指针计算后缀表达式?

转载 作者:行者123 更新时间:2023-11-30 17:36:05 25 4
gpt4 key购买 nike

我必须计算 C 中的后缀表达式。这并不是一个太大的挑战,但我不必使用下标表示法,而只能使用指针进行交互。我对指针非常陌生,需要一些帮助将我拥有的代码(使用下标表示法)转换为仅与指针交互的代码。任何帮助将不胜感激。

//libraries
#include <stdio.h> //for input and output
#include <ctype.h> //for isdigit function
#include <math.h> //for pow function
#define size 50 //size of the array

//global variables
int stack[size];
int top=-1;

//Prototypes
void push(float);
int pop();


//Enter main function
int main(void)
{
char exp[50], c;
int i=0;
float x, y;

//Prompt user to enter equation
printf("Please enter your expression in postfix notation:\n");
//store equation in character array exp
scanf("%s", exp);

//Begin while loop to read through the array
while( (c = exp[i++]) != '\0')
{
//If it is a operand, push
if(isdigit(c))
push(c-'0');

//If it is an operator push two operands on top and evaluate
else
{
x = pop();
y = pop();

//Determining operation done
switch(c)
{
case '+':
push(x + y);
break;
case '-':
push(x - y);
break;
case '*':
push(x * y);
break;
case '/':
push(x / y);
break;
case '^':
push(pow(x,y));
}
}
}

printf("\n\n Evaluated expression will equal: %d\n",stack[top]);
}



void push(float z)
{
stack[++top] = z;
}



int pop()
{
return(stack[top--]);
}

最佳答案

通常,记住这一点就足够了,定义如下:

int xyzzy[10];

这两个是等价的:

xyzzy[4]
*(xyzzy + 4)

这就是您无需实际下标即可访问数组元素的方法。

换句话说,而不是:

stack[++top] = z;
return(stack[top--]);

您可以使用:

*(++top + stack) = z;
return *(top-- + stack);

关于c - 用指针计算后缀表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22804351/

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