【发布时间】:2018-10-09 18:35:52
【问题描述】:
所以,我有一个遍历数组的循环,应该反转连续正数的序列,但它似乎将多余的负数计为序列的一部分,从而改变了它的位置。我自己无法弄清楚错误,很高兴听到任何提示!
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
int Arr[100];
int Arr2[100];
int main()
{
srand(time(NULL));
int n, x;
bool seq = false;
int ib = 0;
printf("Starting array\n");
for (n = 0; n < 100; Arr[n++] = (rand() % 101) - 50);
for (n = 0; n < 100; printf("%3d ", Arr[n++]));
putchar('\n');
for (n = 0; n < 100; n++) //sorting
{
if (Arr[n] > 0) //check if the number is positive
{
if (seq == false) //if it isn't the part of a sequence
{
seq = true; ib = n; //declare it now is, and remember index of sequence's beginning
}
else
seq = true; //do nothing if it isn't first
}
else //if the number is negative
{
if (seq==true) //if sequence isn't null
for (x = n; ib <= n; ib++, x--) //new variable so that n will stay unchanged,
number of iterations = length of sequence
{
Arr2[x] = Arr[ib]; //assigning array's value to a new one,
reversing it in the process
}
seq = false; //declaring sequence's end
Arr2[n + 1] = Arr[n + 1]; //assigning negative numbers at the same place of a new array
}
}
printf("Modified array\n");
for (n = 0; n < 100; printf("%3d ", Arr2[n++]));
putchar('\n');
system('pause');
return 0;
}
【问题讨论】:
-
你能包含声明
n , arr[], arr2[], seq and x的代码吗? -
if (seq = false)-->if(seq == false) -
是的。看起来像错字。不过,如果没有minimal reproducible example,则无法确认。
-
我也不确定
ib <= n;,但如果没有看到数组是如何初始化的,就无法判断。 -
旁注:出现警告级别的现代编译器会将条件中的赋值标记为潜在错误。如果您没有收到警告,请打开警告并将其调高 LOUD。
标签: c++ arrays sorting sequence