Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

c - Getting an unwanted output

In this code, I am experiencing a very frustrating problem.

I have a variable named moves which initial value is set to 0. I also declared a 2d array named a where i refers to its row and j refers to its column.

My target is to increase the value of variable moves until both i and j values are equal to 2.

Now the value of i is 0 and j, 1(given by the user), so basically the value of moves should be = 3.

But my output shows the value of moves is 5.

I think there is a problem in any of the condition statements used in this code below,but I can't figure it out.

#include<stdio.h>
int main()
{
    int a[5][5];
    int i,j,moves=0;
    for(i=0;i<5;i++)
    {
        for(j=0;j<5;j++)
        {
            scanf("%d",&a[i][j]);
        }
    }
    for(i=0;i<5;i++)
    {
        for(j=0;j<5;j++)
        {
           if(a[i][j] == 1)
                break;
        }
        if(a[i][j] == 1)
            break;
    }
    
    //somethings wrong in these loops?
    while(i!=2)
    {
        // i = 0
        if(i<2)
        {
            i=i+1;
            moves=moves+1;
        }
        else if(i>2)
        {
            i=i-1;
            moves=moves+1;
        } 
    }

    while(j!=2) // j=1
    {
        if(j<2)
        {
            j=j+1;
            moves=moves+1;
        }
        else if(j>2)
        {
            j =j-1;
            moves=moves+1;
        }
    }
    printf("%d %d %d", moves, i, j);

}

 Participant's output

  5

 Jury's answer
  3
 Checker comment
  wrong answer 1st numbers differ - expected: '3', found: '5'

this is a problem of codeforces :https://codeforces.com/contest/263/problem/A


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The second if(a[i][j] == 1) in this part

for(i=0;i<5;i++)
{
    for(j=0;j<5;j++)
    {
       if(a[i][j] == 1)
        break;
    }
    if(a[i][j] == 1)
        break;
}

is bad because j may be out-of-range here.

It should be if(j < 5 && a[i][j] == 1).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...