查找数组中数字符号的变化量

Find the amount of changes in the sign of number in an array

本文关键字:变化 符号 数字 数组 查找      更新时间:2023-10-16

基本上,我有一个由"x"个数字组成的数组,我必须输出数组数字中符号变化的次数。

例如,数组为:2-4 5 6 7-2 5-7

输出应该是5。为什么?因为符号第一次在-4改变,第二次在5改变,第三次在-2改变,第四次在5,最后一次在-7改变。共5次。

到目前为止,我有这个,但它并不完美:

#include <iostream>
using namespace std;
int main()
{
int a[50],n,cs=0,ha=0;

cin >> n;
for (int i=0;i<n;i++)
{
    cin >> a[i];
}
for (int j=1;j<=n;j++)
{
    if(a[j]<0 && a[j-1]>0)
    cs++;
    else if(a[j]>0 && a[j-1]<0)
    cs++;
}
cout << cs << endl;
return 0;
}

请帮忙!

您的问题是遇到了未初始化的内存,这导致了未定义的行为。在输入循环中初始化a[0]a[n-1],然后在计算循环中从a[0](j=1和a[j-1])读取到a[n](j=n和a[j])。

只需将其更改为j < n即可。

如果STL是您的一个选项,您可以使用std::adjacent_find。这就是你在一个完整的程序中使用它的方式:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
    vector<int> v { 1 , 3, -5, 8, -9, -10, 4 };
    auto signSwitch = [] (int x, int y) { return (abs(x) == x) ^ (abs(y) == y); };
    int cnt = 0;
    auto i = adjacent_find(begin(v), end(v), signSwitch);
    while (i != end(v))
    {
        cnt++;
        i = adjacent_find(i + 1, end(v), signSwitch);
    }
    cout << cnt;
}

第二个循环应在j < n处终止。

在第二个for循环中,不应该让j转到<=。应该是

 for (int j=1;j<n;j++)