0

我对 C 编程非常陌生。我偶然发现了一些答案。一些使用旧语法。

问题是我必须创建一个程序来读取文本文件并使用读取的后缀行转换为中缀方程。

文本文件将是这样的:

6            #this is the number ofcontainters
1 + 3 4      # it's no_operation_if op!=v then read value of nos mention
2 + 5 6 
3 v 2.1 
4 v 2.4
5 v 3.5 
6 v 1.5

C 文件将在 Ubuntu 终端中读取,其中文本文件是唯一的输入,输出是中缀形式。

关于如何使用结构、数组和联合来完成此任务的一些建议。 我们已经获得了创建 struct opnode、vnode 并将它们联合起来的格式。数组部分我不知道如何从读取转移到数组本身。到目前为止,与 java 相比,C 是如此奇怪。

[编辑]

对不起,我忘了提到这是家庭作业......不再是中缀的后缀。它是解方程的后缀。

在没有语法知识和习惯于面向对象编程的情况下,我不知道如何编辑。

#include <stdio.h>
#include<stdlib.h>
#define MAXLENGTH 512

/* Codes by DocM
 * struct opnode, vnode, union
 */

struct opnode{
char operator
int loperand;
int roperand;
};
struct vnode {
char letterv;
double value;
};
union {
struct opnode op;
struct vnode val;
} nodes[100];

/*node[2].op.loperand
 *node[6].val.value
 */

/* 这会读取终端中输入的文本文件字符串 * 然后命令读取文本文件 * 等等 * 以及其他所有内容 */

int main()
{
char text[MAXLENGTH];
fputs("enter some text: ", stdout);
fflush(stdout);

int i = 0;
int f = 0;

if ( fgets(text, sizeof text, stdin) != NULL )
{
    FILE *fn;
    fn = fopen(text, "r");
}

    /* The code below should be the body of the program
 * Where everything happens.
 */


fscanf (text, "%d", &i);
int node[i];

for(int j = 0; j<i;j++)
{
    int count = 0;
    char opt[MAXLENGTH];
    fscanf(text,"%d %c", &count, &opt);
    if(opt == -,+,*,)
    {
        fscanf(text,"%d %d", &node[j].op.loperand,&node[j].op.roperand);
        node[j].op,operator = opt;
    }
    else
    {
        fscanf(text, "%lf", &node[j].val.value);
    }
    fscanf(text,"%lf",&f);
}
evaluate(1);
return 0;
}

/* Code (c) ADizon below
 *
 */

double evaluate(int i)
{
if(nodes[i].op.operator == '+' | '*' | '/' | '-')
{
    if (nodes[i].op.operator == '+')
    return evaluate(nodes, nodes[i].op.loperator) + evaluate(nodes[i].op.roperator);
    if (nodes[i].op.operator == '*')
    return evaluate(nodes, nodes[i].op.loperator) * evaluate(nodes[i].op.roperator);
    if (nodes[i].op.operator == '/')
    return evaluate(nodes, nodes[i].op.loperator) / evaluate(nodes[i].op.roperator);
    if (nodes[i].op.operator == '-')
    return evaluate(nodes, nodes[i].op.loperator) - evaluate(nodes[i].op.roperator);
}
else
{
    printf nodes[i].val.value;
    return nodes[i].val.value;
}

}
4

1 回答 1

1

I guess the basic algorithm should be:

  • Read the count for number of lines (not sure why this is necessary, would be easier to just keep reading for as long as there is indata provided, but whatever)
  • For each expected line:
    • Parse out the expected four sub-strings
    • Ignore the first, which seems to be a pointless linenumber
    • Print out the substrings in a shuffled order to create the "infix" look
  • Be done

I don't understand the part about the "v" operator, maybe you should clarify that part.

This seems a bit too much like homework for us to just blindly post code ... You need to show your own attempt first, at least.

于 2010-12-02T08:31:33.623 回答