#include <stdio.h>#include <stdlib.h>typedef struct TreeNode { char data; struct TreeNode *left; struct TreeNode *right; } TreeNode, *PtrToNode;PtrToNode createBinaryTree() { char c; scanf("%c", &c); if (c == ' ') { return NULL; } PtrToNode node = (PtrToNode) malloc(sizeof(TreeNode)); node->data = c; node->left = createBinaryTree(); node->right = createBinaryTree(); return node;}int calculate(PtrToNode root) { if (root->left == NULL && root->right == NULL) { return root->data - '0'; } int left = calculate(root->left); int right = calculate(root->right); switch (root->data) { case '+': return left + right; case '-': return left - right; case '*': return left * right; case '/': return left / right; default: return 0; }}int main() { printf("请输入表达式,以回车结束:\n"); PtrToNode root = createBinaryTree(); printf("该表达式的计算结果为:%d\n", calculate(root)); return 0;}电脑运行的命令框显示输入式子后,按回车键无法显示结果,请改正
时间: 2023-12-30 10:02:33 浏览: 81
可以在读取字符后再读取一个字符,用来消耗掉输入式子后的回车符。修改后的代码如下:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
char data;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode, *PtrToNode;
PtrToNode createBinaryTree() {
char c;
scanf("%c", &c);
if (c == ' ') {
return NULL;
}
PtrToNode node = (PtrToNode) malloc(sizeof(TreeNode));
node->data = c;
node->left = createBinaryTree();
node->right = createBinaryTree();
return node;
}
int calculate(PtrToNode root) {
if (root->left == NULL && root->right == NULL) {
return root->data - '0';
}
int left = calculate(root->left);
int right = calculate(root->right);
switch (root->data) {
case '+':
return left + right;
case '-':
return left - right;
case '*':
return left * right;
case '/':
return left / right;
default:
return 0;
}
}
int main() {
printf("请输入表达式,以回车结束:\n");
PtrToNode root = createBinaryTree();
getchar(); // 消耗掉回车符
printf("该表达式的计算结果为:%d\n", calculate(root));
return 0;
}
```
阅读全文