下面的代码是我进行反向波兰符号计算的子程序...基本上是 +、-、* 和 /。程序中的一切正常,除了当我尝试添加 2.5 和 2.5 时,程序给了我 4.0 ......我想我知道为什么,但我不知道如何解决它......现在我正在阅读所有根据此分配的要求从命令行输入数字和运算符,然后获取该字符串并使用 sscanf 从中获取数字...我在想以某种方式包含三个字符'2','.'的数组,和'5',并没有完全转换为浮点数......相反,我认为只是'2'。有人可以看看我的代码并确认或否认这一点,并可能告诉我如何解决它以便我得到正确的答案吗?预先感谢您的任何帮助!
float
fsm (char mystring[])
{
int i = -1, j, k = 0, state = 0;
float num1, num2, ans;
char temp[10];
c_stack top;
c_init_stack (&top);
while (1)
{
switch (state)
{
case 0:
i++;
if ((mystring[i]) == ' ')
{
state = 0;
}
else if ((isdigit (mystring[i])) || (mystring[i] == '.'))
{
state = 1;
}
else if ((mystring[i]) == '\0')
{
state = 3;
}
else
{
state = 4;
}
break;
case 1:
temp[k] = mystring[i];
k++;
i++;
if ((isdigit (mystring[i])) || (mystring[i] == '.'))
{
state = 1;
}
else
{
state = 2;
}
break;
case 2:
temp[k] = '\0';
sscanf (temp, "%f", &num1);
c_push (&top, num1);
i--;
k = 0;
state = 0;
break;
case 3:
ans = c_pop (&top);
if (c_is_empty (top))
return ans;
else
{
printf ("There are still items on the stack\n");
exit (0);
case 4:
num2 = c_pop (&top);
num1 = c_pop (&top);
if (mystring[i] == '+'){
ans = num1 + num2;
return ans;
}
else if (mystring[i] == '-'){
ans = num1 - num2;
return ans;
}
else if (mystring[i] == '*'){
ans = num1 * num2;
return ans;
}
else if (mystring[i] == '/'){
if (num2){
ans = num1 / num2;
return ans;
}
else{
printf ("Error: cannot divide by 0\n");
exit (0);
}
}
c_push (&top, ans);
state = 0;
break;
}
}
}
}
这是我的主要程序:
#include <stdio.h>
#include <stdlib.h>
#include "boolean.h"
#include "c_stack.h"
#include <string.h>
int main(int argc, char *argv[])
{
char mystring[100];
int i;
sscanf("", "%s", mystring);
for (i=1; i<argc; i++){
strcat(mystring, argv[i]);
strcat(mystring, " ");
}
printf("%.2f\n", fsm(mystring));
}
这是带有原型的头文件和 c_stack 的定义:
#include "boolean.h"
#ifndef CSTACK_H
#define CSTACK_H
typedef struct c_stacknode{
char data;
struct c_stacknode *next;
} *c_stack;
#endif
void c_init_stack(c_stack *);
boolean c_is_full(void);
boolean c_is_empty(c_stack);
void c_push(c_stack *,char);
char c_pop(c_stack *);
void print_c_stack(c_stack);
boolean is_open(char);
boolean is_brother(char, char);
float fsm(char[]);
响应六个字母变量:
部分任务是在数组中获取一个包含数字和小数的现有字符串,并使用它们创建一个浮点数,这就是我在这些代码行中所做的:
case 1:
temp[k] = mystring[i];
k++;
i++;
if ((isdigit (mystring[i])) || (mystring[i] == '.')) {
state = 1; } else {
state = 2;
}
break;
case 2:
temp[k] = '\0';
sscanf (temp, "%f", &num1);
c_push (&top, num1);
i--;
k = 0;
state = 0;
break;