所以我应该在1-100之间生成一百个随机数。其中20个应该在1-100的范围内产生,而另外80个应该在40-70的范围内。我也应该创建函数来计算数字的平均值和标准偏差。
请记住,这应该在不使用数组的情况下完成。
我的问题是我不知道如何让我的程序记住生成的数字,以便我可以将它们用于计算功能。我现在所能做的就是通过循环使用它们全部打印出来。我不知道如何使生成的数字可用于计算值。
任何提示,我是否正确地接近这个?
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <time.h>
using namespace std;
int getOutlierScore();
int getNormalScore();
int main()
{
srand (time(NULL));
cout << "The scores are as follows:" <<endl;
for (int i = 1; i <= 20; i++)
{
cout << i << ". " << getOutlierScore() <<endl;
}
for (int i = 21; i <= 100; i++)
{
cout << i << ". " << getNormalScore() <<endl;
}
return 0;
}
int getOutlierScore()
{
int outlier;
outlier = rand() % 100 + 1;
return outlier;
}
int getNormalScore()
{
int max = 70, min = 40;
int normalScore;
normalScore = rand() % (max - min) + min;
return normalScore;
}
答案 0 :(得分:1)
好吧,我不想把答案发给你的家庭作业。我只是指导你如何实现这一目标。
到目前为止,你做得很好。首先,要计算标准差,首先需要找到平均值。这意味着您将不得不计算平均值。
现在,您不需要数组来计算一组数字的平均值。跟踪变量中的这些随机值的总和,如sum
。
您必须将函数getOutlierScore()
和getNormalScore()
中的所有值添加到此变量中。
因此,在循环结束时,您将获得所提供的&#34条件的总和;其中20个应该在1-100范围内生成,而另外80个应该在40-70范围内。&#34;
现在你所要做的就是找到平均值,然后是标准差。 如果你被卡住了,请告诉我。 (练习会帮助你学习,祝你好运!)
修改强> 正如@Doug指出的那样,你也需要平方和。所以在另一个变量中跟踪它。
答案 1 :(得分:0)
class Statistics {
private:
int count;
double sum;
double sum2;
public:
Statistics():count(0), sum(0),sum2(0){}
void clk(float f); // clock in data value
float ave(); // get mean
float std(); // get standard deviation
};
inline void Statistics::clk(float f)
{
count++;
sum += f;
sum2 += f*f;
}
inline float Statistics::ave()
{
return float(sum / count);
}
inline float Statistics::std()
{
return (float)sqrt((double)((sum2 - sum*(sum / count)) / (count - 1)));
}
这应该给你一个开始。您不需要存储任何东西。只需使用带有clk(r)的Statisics对象计时100个随机值。完成后,您可以调用ave()和std()来获得结果。
答案 2 :(得分:0)
好吧,我完全忘了你实际上可以在没有实际存储数字的情况下计算标准偏差。但是,如果您想要存储它们,例如提示它们,您可以使用链接列表。这不是一个数组,因此应该被允许。
一个简单的链接列表(有更优雅的解决方案,但这个很简单)看起来像这样:
struct Node
{
int val;
Node* next;
Node(int val)
{
this->val = val;
next = NULL;
}
void add(int val)
{
Node* cur = this;
while (cur->next)
{
cur = cur->next;
}
cur->next = new Node(val);
}
void deleteFromHere() // delete all Nodes after this one
{
while (next)
{
Node *cur = this;
Node * last;
while (cur->next)
{
last = cur;
cur = cur->next;
}
delete last->next;
last->next = NULL;
}
}
};
并像这样使用它:
int main(void)
{
Node head(getOutlierScore());
for (int i = 0; i < 19; i++)
{
head.add(getOutlierScore());
}
for (int i = 0; i < 80; i++)
{
head.add(getNormalScore());
}
Node* cur = &head;
while (cur->next)
{
cout << cur->val << ". ";
cur = cur->next;
}
cout << endl;
// calculate standard deviation and average here
head.deleteFromHere();
}
顺便说一句,C ++ 11带有<random>
标头,优先于std::rand
。它的用法非常简单。看看这个:
int GetRandom(int min, int max)
{
static random_device rd; // create random device only once per program run
mt19937 mt(rd()); // create number generator
uniform_int_distribution<int> dist(min, max); // define range for the values [min;max]
return dist(mt); // create a random value in range
}