简体   繁体   中英

Sum of negative and positive integers leads to unexpected output - c++

I have an 2D-array, willing to check whether the sum of (every) column is 0 or not. Further more, adding to integers from the array seems to lead to unexpected output.

#include<bits/stdc++.h>
using namespace std;
int main() {
long long int lines;
int temp;
int is_0 = 1;
cin>>lines;
int numbers[3][lines];
for(int i = 0; i < 3; i++){
    for(int j = 0; j < lines; j++){
        cin>>temp;
        numbers[i][j]=temp;
    }
}

for(int i = 0; i<3; i++){
    temp = 0;
    for(int j = 0; j<lines;j++){
        temp += numbers[i][j];          
    }
    cout<<temp<<endl;
}
return 0;
}

example input:

2
1
1
1
-1
-1
-1

example output:

2
0
-2

Any ideas?

The program works as expected. You are creating the following matrix

 1   1
 1  -1
-1  -1

and here

for(int i = 0; i<3; i++){
    temp = 0;
    for(int j = 0; j<lines;j++){
        temp += numbers[i][j];          
    }
    cout<<temp<<endl;
}

You are summing up the numbers of each row.

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