【发布时间】:2022-01-03 20:51:24
【问题描述】:
你能帮我解决这个问题吗?我所能做的就是计算所有的负数。 这是我的代码:
using namespace std;
int main()
{
const int SIZE = 10;
int arr[SIZE]{};
int number=0;
srand(time(NULL));
cout << "Your array is: " << endl;
for (int i=0; i<SIZE; i++)
{
int newValue = rand()%20-10;
arr[i] = newValue;
cout << arr[i] << " ";
if (arr[i] < 0)
{
for (int j=-1; j<SIZE; j++)
{
number = arr[i];
sum += fabs(number);
break;
}
}
}
cout << endl;
cout << "Sum of elements after first element < 0 is: " << sum;
cout << endl;
}
【问题讨论】:
-
只存储第一个负数的索引。 例如
int firstNegativeIndex = -1。如果遇到负数,则使用当前索引对其进行更新,前提是其当前值为 -1。然后,在读入整个数组后,从firstNegativeIndex + 1的值循环到SIZE - 1,并对这些索引处的所有数组值求和。 -
解决这个难题的诀窍是向后思考:从数组的末尾开始添加东西到开头,当你看到一个负数时就停止。这听起来是不是很简单?
-
@SamVarshavchik 但这将是最后一个否定