C++ - 查找数组中第一个和最后一个负数之间的数字

C++ - Find numbers between first and last negative numbers in Array

本文关键字:之间 数字 最后一个 查找 数组 第一个 C++      更新时间:2023-10-16

我得到了关于在数组中查找第一个和最后一个负数之间的数字摘要的问题,这是我的代码:

#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;
}

输出与上所示相同。