Random numbers picked from array that sums up to a float

最后都变了- 提交于 2021-01-29 17:23:16

问题


So I try to pick 15 random numbers from my array that their sum adds up to 47826.53 but doesn't work.

My k is not incrementing.

#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;

int main ()
{
  float x[23] =
    { 6653.05, 1939.89, 6649.05, 2755.74, 5270.62, 6216.57, 4812.92, 7919.50,
    4807.46, 1698.00, 849.01, 1415.01, 1698.00, 4811.61, 1698.21, 7355.99,
    4817.37,
    566.75, 2266.47, 1699.86, 3966.33, 849.93, 849.93
  };
  int v[22] = { 0 };
  float s = 0;
  int k = 0;
  int RandIndex = 0;

  while (s != 47826.53)
    {
      RandIndex = rand () % 24;
      if (v[RandIndex] == 0 && RandIndex != 0)
    {
      s = s + x[RandIndex];
      k++;
      v[RandIndex] = 1;
      cout << s << " ";
    }
      if (k > 15 || s > 47826.53)
    {

      for (int i = 0; i <= 22; i++)
        v[i] = 0;
      k = 0;
    }

    }
  cout << s;
  for (int i = 1; i <= 23; i++)
    if (v[i] != 0)
      cout << "Number :" << x[i];
  return 0;
}

来源:https://stackoverflow.com/questions/59805786/random-numbers-picked-from-array-that-sums-up-to-a-float

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!