C++ 从数组中选择的随机数,其总和为浮点数
所以我试着从数组中选取15个随机数,它们的总和为47826.53,但不起作用 我的C++ 从数组中选择的随机数,其总和为浮点数,c++,random,C++,Random,所以我试着从数组中选取15个随机数,它们的总和为47826.53,但不起作用 我的k不是递增的 #包括 #包括 #包括 使用名称空间std; int main() { 浮动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
k
不是递增的
#包括
#包括
#包括
使用名称空间std;
int main()
{
浮动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};
浮点数s=0;
int k=0;
int RandIndex=0;
而(s!=47826.53)
{
RandIndex=rand()%24;
如果(v[RandIndex]==0&&RandIndex!=0)
{
s=s+x[RandIndex];
k++;
v[RandIndex]=1;
库特(47826.53)
{
对于(int i=0;i这是完整的代码,具体来说,为什么你期望15个随机数加起来正好是47826.53呢?即使存在15个数的子集,加起来的总数,精确选择该子集的概率很小,所以你将在该循环中很长一段时间。th的最终目标是什么e练习?你真正想解决的问题是什么?这看起来像一口井。我知道总共有15个数字。它们是付款,我知道15个是从23开始支付的,但不知道是哪一个。@Igor tandetnikalo,你的索引是关闭的。rand()%24
生成一个从0到23(包括0到23)的数字。进入x[23]的有效索引是0到22;进入v[22]的有效索引
是0到21。你莫名其妙地放弃了0的RandIndex
,而22或23的索引将超出v
或x
或两者的界限。你认为随机尝试组合是找到正确组合的最佳方式吗?我的猜测是,宇宙将在你的程序达到目标之前遭受热死亡回答。
#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;
}