gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:29:31 24 4
gpt4 key购买 nike

我必须在 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/

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