c - Stack 的静态实现无法正常工作

标签 c

我必须在 C 上编写一个程序,允许用户输入一堆 float ,然后 progmar 应该打印堆栈。我试图让它工作,但看起来我搞砸了一些东西,因为它正确地返回了堆栈的所有元素,但也返回了“堆栈为空”“堆栈的元素是:0.0000”毕竟屏幕上其他不为0的元素...

到目前为止,这是我的代码:

#include <stdio.h>
#include <stdlib.h>
float stack[10];
int top=-1;
void Write(float x)
{
     if(top==9)
     printf("The stack is Full ! \n");
     else
     {
         top++;
         stack[top]=x;
         }
}
float Read()
{
      if(top==-1)
      {
                 printf("The stack is empty ! \n");
                 return 0;
                 }
      else
      {
          float value;
          value=stack[top];
          top--;
          return value;
          }
}

int main()
{
  float x;
  do
  { 
  printf("Molq vyvedete razlichen ot nula element na stecka: ");
  scanf("%f", &x);  
  if(x!=0.0)  
  Write(x);
}while(x!=0.0);
  do 
  {
              x=Read();
              printf("Elementite na stecka sa: %f \n", x);
}while(x!=0.0);   

  system("PAUSE"); 
  return 0;
}

如何消除屏幕元素上显示的空堆栈信息和 0.0000?

最佳答案

首先,您的程序中存在错字。您将一个函数命名为 Read 但可以像 read 一样调用它。

另一个问题是逻辑错误。在这个循环中

  do
  { 
  printf("Please enter differentt then 0 element of the stack: ");
  scanf("%f", &x);    
  write(x);
}while(x!=0.0);

值 0.0 将被放入堆栈中。所以下一个循环

  do
  {
              x=read();
              printf("The elements of the stack are: %f \n", x);
}while(x!=0.0); 

在读取堆栈中等于 0.0 的顶部值后停止迭代,

至少改变第一个循环

  do
  { 
  printf("Please enter differentt then 0 element of the stack: ");
  scanf("%f", &x);    
  if ( x != 0.0 ) write(x);
}while(x!=0.0);

如果加上empty和full之类的函数就更好了。

在这种情况下,循环可以这样写

while ( !full() )
{
      printf("Please enter differentt then 0 element of the stack: ");
      scanf("%f", &x);    
      write(x);
}

while ( !empty() )
{
     x=read();
     printf("The elements of the stack are: %f \n", x);
}

关于c - Stack 的静态实现无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29052191/

相关文章:

c++ - OpenSSL SSL_shutdown 收到信号 SIGPIPE,Broken pipe

c - C 中的数据隐藏,多态行为?

c - 为什么会出现段错误?

c - C中的"identifier not found"

c - c集成程序中的舍入错误

c - 绘制带星号的三角形 int 时出现问题

c - 从二维字符数组初始化指向字符的指针数组

c - 读写位置之间的距离对缓存性能有影响吗?

c - 从c中的命令行读取的字符串中打印转义字符

c++ - 如何查看VisualStudio对C/C++标准库的实现?