gpt4 book ai didi

C:数组中的第一个数字由于未知原因变为 0

转载 作者:行者123 更新时间:2023-11-30 14:49:13 25 4
gpt4 key购买 nike

计划:
这应该是一个简单的反向波兰符号添加程序,请忽略 EOF 中断,它是一个占位符。输入是 c,始终是一个数字,它会被传输到 x,其中每个下一个数字 c 将添加到数字 x,因此,例如,当我们输入 c 作为 1,2 和 3 时,x 将是 123。当我们输入“e”时,它会标记一个新数字的开始,整个堆栈被推回后,x将被转移到stack[0]中,x将变为0。当输入“+”发生加法时,最后两个数字将被相加,x 和堆栈中的第一个数字,或者堆栈中的第一个和第二个数字,或者堆栈中的第一个数字将重复自身。

问题:
堆栈数组中的第一个数字将随机变为 0,我看不到我在哪里犯了错误。第一个数字(stack[0])仅在开始时获得零值,再也不会。有时输入“+”时它只会得到一个值。

    #include <stdio.h>
#include <stdlib.h>

int main()
{
int stack[16];
int x;
int i;
char c;
//int c;
x=0;

for (i = 0; i < 16; i++)
{
stack[i]=0;
}

while(1)
{
//input character
scanf("%s", &c);

if (c == EOF) break;
//put x to stack
else if (c == 'e')
{for (i = 15; i >0; i--)
{
stack[i]=stack[i-1];
}
stack[0] = x;
x = 0;
}
//reverse polish addition
else if (c == '+')
//if x is 0 go immediately to the stack
{if (x == 0)
//if both x and the second number in array are 0 just duplicate the first number
if (stack[1] == 0)
stack[0] = stack[0] + stack[0];
//if only x is 0 add the first number on the second
else
{
stack[0]=stack[0]+stack[1];
//push back the array to fill the gap on the second number
for (i = 1; i <15; i++)
{
stack[i]=stack[i+1];
}

}
else
{
stack[0] = stack[0] + x;
x = 0;
}
}
else
{
x = x * 10 + ((int)c-0x30);
// putchar(c);
}
printf("X=%d\n",x);
//print stack
for (i = 0; i < 16; i++)
{
printf("%d \t",stack[i]);
}
printf("\n");
}
return 0;
}

最佳答案

问题 1

scanf("%s", &c); 导致未定义的行为。使用 scanf("%c", &c);

问题2

使用 scanf 时,

c 永远不会等于 EOF。因此,下面的行是没有用的。

    if (c == EOF) break;
<小时/>

下面将解决这两个问题。

// Use " %c" instead of "%c" to skip leading whitespace characters.
while ( scanf(" %c", &c) == 1 )
{
}

关于C:数组中的第一个数字由于未知原因变为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49804015/

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