gpt4 book ai didi

c - C 语言 RPN 计算器

转载 作者:行者123 更新时间:2023-11-30 16:58:50 26 4
gpt4 key购买 nike

有人可以解释一下为什么我在 myString 上使用 strok() 后总是出现乱码吗?我的输出图片位于底部。我尝试将 myString 中的每个元素初始化为 NULL 字符,但我的代码仍然不起作用:(

预期输出:

enter image description here

我的输出:

enter image description here

int main()
{
int i;
char myString[60];
char *token;
float result;
float x;
float y;
struct Stack myStack;
StackInit(&myStack);


BOARD_Init();

printf("\nWelcome to my RPN calculator.\n");
printf("Enter floats and + - / * in RPN format: \n >");

for (i = 0; i < sizeof (myString); i++) {
myString[i] = '\0';
}

fgets(myString, sizeof (myString), stdin);



token = strtok(myString, " ");
while (token != NULL) {
printf("%f\n", atof(token));
token = strtok(NULL, " ");

if (atof(token) != 0) {
StackPush(&myStack, atof(token));
} else if (*token == '+') { // if token is addition
StackPop(&myStack, &y);
StackPop(&myStack, &x);
result = x + y;
StackPush(&myStack, result);

} else if (*token == '-') { // if token is subtraction
StackPop(&myStack, &y);
StackPop(&myStack, &x);
result = x - y;
StackPush(&myStack, result);
} else if (*token == '*') { // if token is multiplication
StackPop(&myStack, &y);
StackPop(&myStack, &x);
result = x * y;
StackPush(&myStack, result);
} else if (*token == '/') { // if token is division
StackPop(&myStack, &y);
StackPop(&myStack, &x);
result = x / y;
StackPush(&myStack, result);
}

}




while (1);

}

最佳答案

正如 @BLUEPIXY 在评论中指出的,您的代码在这里有问题:

token = strtok(myString, " ");   // Here you get the first sub string
while (token != NULL) {
printf("%f\n", atof(token));
token = strtok(NULL, " "); // Here you get the second sub string
// and throw away the first substring
// So all the code below is never executed
// for the first substring.
// In other words: You never push the first
// float to the stack

if (atof(token) != 0) {
StackPush(&myStack, atof(token));

您应该做的是将 token = strtok(NULL, ""); 移动到循环末尾:

while (token != NULL) {
printf("%f\n", atof(token));
// Not here............. token = strtok(NULL, " ");

if (atof(token) != 0) {
StackPush(&myStack, atof(token));
} else if (*token == '+') { // if token is addition
//...
//...
}

token = strtok(NULL, " "); // but here
}

关于c - C 语言 RPN 计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38519214/

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