简体   繁体   中英

calculating every consecutive integers sum in array

I have an array like the following ([2][10] size):

5 | 13 | 12 | 2 | 7 | 12 | 3 | 1 | 4 | 5
1 | 10 | 5 | 1 | 14| 6 | 4 | 1 | 7 | 2
4 | 9 | 17 | 5 | 6 | 2 | 7 | 21 | 8 | 1

The user will enter a number, the code will compute sum of consecutive numbers and it will return starting row and column back.

ex: input = 48 and return row = 1, column = 1
input = 36 and return row = 2, column = 6

My sample code it returns only "finished" instead of row = 0, column = 1. What's wrong?

int sum;
int column;
int row;
bool situ = false;
int number = 12;
int puzzle[] = { (4,6,5,1,2), (3,5,6,7,8) };

for(int i=0; i<2; i++)
{
    sum = 0;
    for(int j=0; j<6; j++)
    {
        sum = 0;
        for(int k=j; k<6; k++)
        {
            sum += puzzle[j];
            if( number == sum && !situ)
            {
                row = i;
                column = k;
                cout << "row = " << i << endl;
                cout << "column = " << j << endl;

            }
            if( !situ)
                break;
        }
        if( !situ)
            break;
    }
    if( !situ)
        break;
}
cout << "finished";

Your

if( !situ)
    break;

statements are a problem. You initialize situ to false and never change it. Hence, you always break after the first loop.

    #include<iostream>

using namespace std;
int main()
{
int sum;
int column;
int row;
bool situ = false;
int number = 12;
int puzzle[2][10] = { {4,6,5,1,2}, {3,5,6,7,8} };

for(int i=0; i<2; i++)
{
    sum = 0;
    for(int j=0; j<5; j++)
    {
        sum = 0;
        for(int k=j; k<5; k++)
        {
            sum += puzzle[i][k];
            if( number == sum && !situ)
            {
                row = i;
                column = k;
                cout << "row = " << i << endl;
                cout << "column = " << j << endl;

            }
     //       if( !situ)
    //            break;
        }
 //       if( !situ)
//            break;
    }
 //   if( !situ)
//        break;
}

cout << "finished";
}enter code here

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