Answer the question
In order to leave comments, you need to log in
Swap the 1st negative and last positive elements in the matrix. How to fix the error?
Faced a small problem. How to fix an error when rearranging elements in a matrix? I need to swap the first negative and last positive elements in the output array. When outputting to the 2nd listBox, the result is incorrectly displayed for me. How to fix this problem?
private void button2_Click(object sender, EventArgs e)
{
int indexOfNegativeElement = -1;
int indexOfPositiveElement = -1;
for (int i = 0; i < 10; i++)
{
if (mas[i] < 0)
{
listBox2.Visible = true;
indexOfNegativeElement = i;
break;
}
else
{
label1.Visible = true;
}
}
for (i = 9; i > -1; i--)
{
if (mas[i] > 0)
{
listBox2.Visible = true;
indexOfPositiveElement = i;
break;
}
else
{
label1.Visible = true;
}
}
if (indexOfNegativeElement >= 0 && indexOfPositiveElement <= 0)
{
int temp = mas[indexOfNegativeElement];
mas[indexOfNegativeElement] = mas[indexOfPositiveElement];
mas[indexOfPositiveElement] = temp;
}
listBox2.Items.Add(mas[i].ToString());
if (indexOfNegativeElement <= 0 && indexOfPositiveElement >= 0)
{
int temp = mas[indexOfNegativeElement];
mas[indexOfNegativeElement] = mas[indexOfPositiveElement];
mas[indexOfPositiveElement] = temp;
}
listBox2.Items.Add(mas[i].ToString());
}
Answer the question
In order to leave comments, you need to log in
I didn’t go into logic much, but what immediately caught my eye was that the indexOfPositiveElement variable gets an init.value of -1, and then it may not change after any checks. After that, you test it for less than or equal to zero. And in this case, even without the fact that you have found a positive element, you still want to rearrange the values. The same is true for the indexOfNegativeElement variable. I marked both places in bold type.
if (indexOfNegativeElement >= 0 && indexOfPositiveElement <= 0 )
{
int temp = mas[indexOfNegativeElement];
mas[indexOfNegativeElement] = mas[indexOfPositiveElement];
mas[indexOfPositiveElement] = temp;
}
listBox2.Items.Add(mas[i].ToString());
if ( indexOfNegativeElement <= 0 && indexOfPositiveElement >= 0)
{
int temp = mas[indexOfNegativeElement];
mas[indexOfNegativeElement] = mas[indexOfPositiveElement];
mas[indexOfPositiveElement] = temp;
}
listBox2.Items.Add(mas[i].ToString());
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question