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

时间:2017-11-09 10:45:26

标签: c++ arrays algorithm iterator

我得到的问题是在第一个和最后一个负数之间找到数字的数字摘要,这里是我的代码:

#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。

2 个答案:

答案 0 :(得分:0)

一种可能的解决方案:

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

如果没有评论,应该很清楚。

答案 1 :(得分:0)

此循环

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

输出与上面显示的相同。