为什么我写的程序会出现输出延后?
如图,我是按照左边网页上的输入样例输入的,根据我的程序,输入 8 后就应该出现 ‘here',可直到下一次输入时才出现,而且根据我的程序,输完 A 1 2 后就应该执行
printf("Element = %c, cl = %c, cr = %c\n", T[i].Element, cl, cr);
但是并没有执行。
也就是我的程序中的
printf("here\n");
for (i = 0; i < n; i++) {
printf("i = %d, n = %d\n", i, n);
scanf("%c %c %c\n", &T[i].Element, &cl, &cr);
printf("Element = %c, cl = %c, cr = %c\n", T[i].Element, cl, cr);
整个的执行顺序都不一样,为什么会是这样呢?
我的每一次输入输出都会延后一个,这是怎么回事?
而且最后输完 8 个后,还需要多输几个字符才能开始运行程序,这是怎么回事,求大神指教:)
#include <stdio.h>
#include <string.h>
#define MaxTree 10
#define ElementType char
#define Tree int
#define Null -1
struct TreeNode
{
ElementType Element;
Tree Left;
Tree Right;
} T1[MaxTree], T2[MaxTree];
Tree BuildTree(struct TreeNode T[]);
int Isomorphic(Tree R1, Tree R2);
int main()
{
Tree R1, R2;
R1 = BuildTree(T1);
R2 = BuildTree(T2);
printf("hr3\n");
if (Isomorphic(R1, R2))
printf("Yes\n");
else
printf("No\n");
return 0;
}
Tree BuildTree(struct TreeNode T[])
{
printf("hr1\n");
int n, i;
scanf("%d\n", &n);
int check[n];
char cl, cr;
int Root = -1;
if (n) {
for (i = 0; i < n; i++) {
check[i] = 0;
}
printf("here\n");
for (i = 0; i < n; i++) {
printf("i = %d, n = %d\n", i, n);
scanf("%c %c %c\n", &T[i].Element, &cl, &cr);
printf("Element = %c, cl = %c, cr = %c\n", T[i].Element, cl, cr);
if (cl != '-') {
T[i].Left = cl - '0';
check[T[i].Left] = 1;
}
else
T[i].Left = Null;
if (cr != '-') {
T[i].Right = cr - '0';
check[T[i].Right] = 1;
}
else
T[i].Right = Null;
}
for (i = 0; i < n; i++) {
if (!check[i])
break;
}
Root = i;
}
return Root;
}
int Isomorphic(Tree R1, Tree R2)
{
printf("hr3\n");
if ((R1 == Null) && (R2 == Null))
return 1;
if (((R1 == Null) && (R2 != Null)) || ((R1 != Null) && (R2 == Null)))
return 0;
if (T1[R1].Element != T2[R2].Element)
return 0;
if ((T1[R1].Left == Null) && (T2[R2].Left == Null)) {
//printf("hr3\n");
return Isomorphic(T1[R1].Right, T2[R2].Right);
}
if (((T1[R1].Left != Null) && (T2[R2].Left != Null)) && ((T1[T1[R1].Left].Element) == (T2[T2[R2].Left].Element))) {
// no need to swap the left and the right
//printf("hr4\n");
return (Isomorphic(T1[R1].Left, T2[R2].Left) && Isomorphic(T1[R1].Right, T2[R2].Right));
}
else { //need to swap the left and the right
//printf("hr5\n");
return (Isomorphic(T1[R1].Left, T2[R2].Right) && Isomorphic(T1[R1].Right, T2[R2].Left));
}
}
这是因为题主在
int scanf( const char* format, ... );
函数中的格式参数format
设置导致的。题主可以做几个小测试:
把
(1)
处的语句换成scanf("%d", &n);
。把
(2)
处的语句换成scanf(" %c %c %c\n", &T[i].Element, &cl, &cr);
。把
(2)
处的语句换成scanf("%c %c %c", &T[i].Element, &cl, &cr);
。把
(2)
处的语句换成scanf(" %c %c %c", &T[i].Element, &cl, &cr);
。具体原因可以参考这里和这里关于格式参数
format
设置的说明,下面引用比较重要的几点: