I have written the following code:
#include<iostream>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
int main()
{
int t,n,input;
vector<int> neg, pos;
cin>>t;
while(t--)
{
cin>>n;
for(int i=0;i<n;i++)
{
cin>>input;
if(input<0)
neg.push_back(input);
else
pos.push_back(input);
}
sort(neg.begin(),neg.end());
sort(pos.begin(),pos.end());
for(int i=0;i<neg.size();i++)
{
for(int j=pos.size()-1;j>=0;j--)
{
if(neg[i]+pos[j]==0)
cout<<neg[i]<<" "<<pos[i];
}
cout<<"\n";
}
cout<<endl;
neg.clear();
pos.clear();
}
return 0;
}
which is the solution to the following problem: GeeksForGeeks Problem
What I'm trying to do: Keep negative and positive integers in 2 separate vectors. I add the numbers using 2 loops. If the sum is zero for any two combinations, I print them.
The Problem: The code does something weird. It prints -3, 1 (-3+1==0 is given as true) as a combination which is wrong. Why is code acting in such a way and what is the possible solution?
Aucun commentaire:
Enregistrer un commentaire