查找数组中数字符号的变化量
Find the amount of changes in the sign of number in an array
基本上,我有一个由"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++)
相关文章:
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 将无符号char*转换为std::istream*C++
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- vscode g++链路故障:体系结构x86_64的未定义符号
- C++取消引用指针.为什么会发生变化
- 为什么在读取文件大小时文件IO速度会发生变化
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 如何理解将半精度指针转换为无符号长指针和相关的内存对齐
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- 使用gcc从静态链接的文件中查找可选符号
- C++中无符号字符溢出
- 使用无符号字符数组有效存储内存
- C++:Application.cpp中抛出了未解析的外部符号(解决方案在问题的末尾,供未来的读者参考)
- VC++本机单元测试,找不到调试符号
- 创建集合成员(C )成员的每个置换和符号变化的集合
- "signbit"与乘法检测到的符号变化,并将其与零进行比较
- c++中加法符号的变化
- 处理c++角度中的符号变化
- 查找数组中数字符号的变化量