简体   繁体   中英

Some questions about Scanf

What's the differences between the next three codes.

1:

struct node
{
    int data;
}tree[100050];
/*
some codes
*/
int main()
{
    int tot;
    scanf("%d",&tot);
    int tmp;
    for(int i=0;i<=tot;++i){
        scanf("%d",&tmp);
        tree[i].data=tmp;
        insert(i,1);
    }
}

Wrong Answer

2:

struct node
{
    int data;
}tree[100050];
/*
some codes
*/
int main(){
    int n;
    scanf("%d",&n);
    int tmp;
    for(int i=0;i<=n;++i){
        scanf("%d",&tree[i].data);
        insert(i,1);
    }
}

Accepted

3:

struct node
{
    int data;
}tree[100050];
/*
some codes
*/
int main()
{
    int tot;
    scanf("%d",&tot);
    int tmp;
    for(int i=0;i<=tot;++i){
        scanf("%d",&tmp);
        tree[i].data=tmp;
        insert(i,1);
        tmp=0;
    }
}

Accepted

The first codes can not pass all tests, but next two codes can pass all tests.

The problem is here POJS024 。It is written in Chinese. Input is a list of number which builds a Binary Sort Tree,the first number is the root. Output the In-Order Traversal and the Post-Order Traversal。

All three use wrong logic. You got lucky in the second and third, probably because insert has some special handling of values that are equal to 0.

The mistake in all three is that you are using

for(int i=0;i<=n;++i){

instead of

for(int i=0;i<n;++i){
             ^^^ Needs to be < not <=

If you had code to check the return value of scanf , you would have caught your error sooner.

if ( scanf(...) == 1 )
{
    insert(i,1);
}

That's why it's very important that you make a habit of checking the return value of scanf family of functions ALWAYS to make sure that you were able to read all data that you were expecting to.

The problem (which actually exists in some sense in all three cases) is that you call scanf() one too many times because you're using a <= comparison in the for loop instead of the using the < comparison. As a result the last call to scanf() actually fails. and you call insert(i,1) one more time than it should be called.

In example 1 that results in tree[i].data being set to the last value that was read into tmp , in examples 2 and 3 that value is left at zero. Apparently the extra call to insert(i,1) doesn't cause a problem in that particular scenario.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM