C++ - 查找数组中第一个和最后一个负数之间的数字
C++ - Find numbers between first and last negative numbers in Array
我得到了关于在数组中查找第一个和最后一个负数之间的数字摘要的问题,这是我的代码:
#include <iostream>
using namespace std;
int main(){
float a[] = { 1.5, 55, 5, 4.4,7.1,9,8,2,4.2, -3, -3.2, 5.2, -9 };
float eq = 0;
float sumofnums = 0;
for (int g = 0; g < 13; g++) {
if (a[g] < 0) {
sumofnums = a[g];
cout << sumofnums << endl;
}
}
我想找到第一个和最后一个负数之间的摘要,我尝试了这种方法:sumofnums+= a[g]; 但答案是-15.2,而实际上是-10。
一种可能的解决方案:
#include <iostream>
using namespace std;
int main() {
float a[] = { 1.5, 55, 5, 4.4,7.1,9,8,2,4.2, -3, -3.2, 5.2, -9 };
float sumofnums = 0;
int size = sizeof(a) / sizeof(a[0]); // size is 13 here, this allows you
// to determine the size automatically
int first = 0;
int last = size - 1;
for (int g = 0; g < size; g++) {
if (a[g] < 0) {
first = g;
break;
}
}
for (int g = size - 1; g >= 0; g++) {
if (a[g] < 0) {
last = g;
break;
}
}
for (int g = first; g <= last; g++) {
sumofnums += a[g];
}
cout << "Sum is " << sumofnums << endl;
}
它应该足够清楚,没有评论。
此循环
for (int g = 0; g < 13; g++) {
if (a[g] < 0) {
sumofnums = a[g];
cout << sumofnums << endl;
}
}
按顺序将数组的负值分配给变量sumofnums
,而不是累加所需范围内的所有值。
如果使用标准算法,那么程序可能看起来像
#include <iostream>
#include <iterator>
#include <algorithm>
#include <numeric>
#include <functional>
int main()
{
float a[] = { 1.5, 55, 5, 4.4, 7.1, 9, 8, 2, 4.2, -3, -3.2, 5.2, -9 };
float sumofnums = 0.0f;
auto first = std::find_if(std::begin(a), std::end(a),
std::bind2nd(std::less<float>(), 0.0f));
if (first != std::end(a))
{
auto last = std::find_if(std::rbegin(a), std::rend(a),
std::bind2nd(std::less<float>(), 0.0f)).base();
sumofnums = std::accumulate(first, last, sumofnums);
}
std::cout << sumofnums << std::endl;
return 0;
}
它的输出是
-10
如果使用手动编写的循环,则程序可能如下所示
#include <iostream>
int main()
{
float a[] = { 1.5, 55, 5, 4.4, 7.1, 9, 8, 2, 4.2, -3, -3.2, 5.2, -9 };
const size_t N = sizeof(a) / sizeof(*a);
float sumofnums = 0.0f;
const float *first = a;
while (not (first == a + N) and not (*first < 0.0f))
{
++first;
}
if (first != a + N )
{
const float *last = a + N;
while (not (last == a) and not (*(last - 1 ) < 0.0f))
{
--last;
}
for (; first != last; ++first) sumofnums += *first;
}
std::cout << sumofnums << std::endl;
return 0;
}
输出与上所示相同。
相关文章:
- 在数字之间插入 + 或 - 符号以使其等于整数
- 将向量之间的数字放在另一个向量之间<vector>>如果两个数字的差值为 1
- 获取 2 个数字之间的差异百分比
- 两个有符号数字之间的距离
- 无法理解代码背后的逻辑,这是在两个给定数字之间生成素数的优化问题
- C++:这两种将数字写入矩阵的方式之间是否存在显着的速度差异?
- 如何从txt文件c++中提取括号之间的数字
- 正则表达式匹配字符串之间的数字
- C++显示两个区间之间的数字的程序检查一个数字是否可以表示为两个素数的总和
- 数字之间的比较
- 在没有比较运算符的情况下查找 2 个数字之间的最小值
- 在[a,b]间隔之间找到相同的数字
- 不理解连续数字之间的空格代码
- 如果 2 个数字之间的差值在 1 到 100 之间,则应运行 if 语句
- 第一个和第二个数字之间能被 4 和 6 整除的所有整数的总和
- 0 和 n 之间有多少个数字满足按位属性 i&y==i?
- 2 个给定数字之间的双精度密度
- 三个数字之间的 C++ 相加两个更高的数字,没有循环和数组
- 我如何生成2D数组,在行和列之间具有不同的数字
- 给定n个数字,编写一个例程,以在4个连续数字之间找到最大的数字