问题
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