سؤال

I guess there is a problem in scanning the values from keyboard to the stack array using scanf. I'm not sure how to enter scanned values to the array in the stack. Please correct my C code. Check my main method where I ask for user inputs and try to push them to the array.

#include<stdio.h>
#define STACKSIZE 5

struct stack
{
    float data[STACKSIZE];
    int sp;
};

struct stack sta={{0},-1};

//push method
void push(float n)
{
    sta.data[++sta.sp]==n;
    //onlystack.data[++onlystack.sp]=x;  
}

//pop method
float pop()
{  
    return sta.data[sta.sp--];
}

//top method
float top()
{
    return sta.data[sta.sp];
}

//full method
int full()
{
    return (sta.sp==STACKSIZE-1);
}

//empty method
int empty()
{
    return (sta.sp==-1);
}

int main()
{
    int x, y;
    int temp;
    for (x=0; x<STACKSIZE; x++)
    {
        **printf("Enter float to be stored in the stack");
        scanf("%f", &temp);
        push(temp);**
    }

    while(!empty(sta))
    {
        for (y=0; y<STACKSIZE; y++)
        {
            printf("\t%f",pop());
        }
    }

    printf("%f", top());
    return 0;
}
هل كانت مفيدة؟

المحلول

Thoughts:

  1. In push(), you test for equality instead of performing assignment.
  2. temp is of type int. It should be a float.
  3. empty() takes no arguments, and you pass it one.
  4. The last printf("%f", top()) will invoke undefined behavior, because you will print sta.data[-1].
  5. You don't really need the while loop and the for loop around the pop() printing. You should be able to just do the while loop.
  6. To make your output more readable, you should probably print '\n' characters after each float, which will make each float be seen on their own line.

Once these errors are fixed, the code appears to work correctly:

نصائح أخرى

A major problem here is that you give the format "%f" (for floating point) to scanf, but you give it a pointer to an int. This will cause the value to be something completely unexpected.

Also, in the loop where you print the values, why have a nested loop? The outer loop is all that's needed.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top