gpt4 book ai didi

找不到这个简单的 C 代码有什么问题

转载 作者:行者123 更新时间:2023-11-30 20:25:42 24 4
gpt4 key购买 nike

这是一个简单的树插入和遍历代码。

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

struct tree
{
struct tree *left;
struct tree *right;
int value;
};

typedef struct tree node;

void insertNode(node **root, int val)
{
node *temp = NULL;
if(!(*root))
{
temp = (node*) malloc(sizeof(node));
temp->value = val;
temp->left = NULL;
temp->right = NULL;
*root = temp;
}

if(val < (*root)->value)
insertNode(&(*root)->left, val);

if(val >= (*root)->value)
insertNode(&(*root)->right, val);
}

void preOrder(node *root)
{
if(root)
{ printf(" %d",root->value);
preOrder(root->left);
preOrder(root->right);
}
}

void inOrder(node *root)
{
if(root)
{
inOrder(root->left);
printf(" %d",root->value);
inOrder(root->right);
}
}

void postOrder(node *root)
{
if(root)
{
postOrder(root->left);
postOrder(root->right);
printf(" %d",root->value);
}
}

void delTree(node *root)
{
if(root)
{
delTree(root->left);
delTree(root->right);
free(root);
}
}

int main()
{
int val;
char ch; ch = 'y';
node *root;

while(ch == 'y')
{
scanf("Enter the node value: %d", &val);
insertNode(&root, val);
scanf("Want to enter more: %c", &ch);
}

printf("\nInOrder traversal:\n");
inOrder(root);
printf("\nPreOrder traversal:\n");
preOrder(root);
printf("\nPostOrder traversal:\n");
postOrder(root);

delTree(root);
printf("Tree Deleted.");

return 0;
}

代码看起来没有问题,也没有显示错误。虽然编译时显示警告;

ignoring return value of ‘int scanf(const char*, ...)’, declared with attribute

这似乎是因为忽略了scanf的返回值而启动的,来自ignoring return value of ‘int scanf(const char*, ...)’, declared with attribute warn_unused_result [-Wunused-result]? .

但即使抑制警告并编译可执行文件也不会接受任何输入。这是为什么。我正在 CodeBlocks IDE 上运行代码。

ideone 上的情况相同,http://ideone.com/jOnjEK .

如有任何帮助或建议,我们将不胜感激。

最佳答案

scanf("输入节点值:%d", &val); 应该是

scanf("%d", &val);

scanf("想要输入更多:%c", &ch); 应该是

scanf(" %c", &ch);

假设您打算这样做

printf("Enter the node value:\n");
if(scanf("%d", &val) != 1)
{
printf("Integer not read \n");
break;
}

printf("Want to enter more:\n");
if(scanf(" %c", &ch) != 1)
{
printf("character not read\n");
break;
}

记下 scanf()%c 之前的空格

关于找不到这个简单的 C 代码有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27746581/

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