从功能到功能获取随机数

Jer*_*arp 2 c++ visual-c++

相对较新的C++,这已经困扰了我一段时间.我正在尝试编写一个程序,它会根据生成的随机数做不同的事情.

为了解释我想要做的事情,我们假设我正在创建一个运动员名单,并开始在一定范围内随机生成他们的高度.容易没问题.说然后我想根据他们的身高来产生他们的体重.这是事情变得混乱的地方.出于某种原因,我无法弄清楚,该程序是根据与首先返回的高度不同的高度随机生成权重.我只是不明白.

无论如何,这是一段(非常简化的)示例代码,希望能够展示我正在尝试做的事情.我确定我错过了一些明显的东西,但我似乎无法弄明白.

#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <time.h>
using namespace std;

int random(int min, int max, int base)
{
    int random = (rand() % (max - min) + base);

    return random;
}

int height()
{
    int height = random(1, 24, 60);

    return height;
}

int weight()
{
    int weight = height() * 2.77;

    return weight;
}

void main()
{
    srand ((unsigned int)time(0));

    int n = 1;

    while (n <= 10)
        { 
        cout << height() << " and " << weight() << endl;
        ++n;
        }

    return;
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*lia 5

weightheight 再次呼叫,它显然会生成一个不同的数字(这是RNG的全部意义:)).

要获得您想要的效果,您可以:

  • 更改weight为接受height作为参数; 然后,在main每次迭代中,保存height临时变量返回的值并将其传递给高度以获得相应的高度;

    int weight(int height)
    {
        return height*2.77;
    }
    
    // ... inside the main ...
    while (n <= 10)
    { 
        int curHeight=height();
        cout << curHeight << " and " << weight(curHeight) << endl;
        ++n;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 移动heightweight一类,将存储height作为一个私有字段,添加nextPerson,将内场升级到一个新的随机值成员.

    class RandomPersonGenerator
    {
        int curHeight;
    public:
        RandomPersonGenerator()
        {
            nextPerson();
        }
    
        int height() { return curHeight; }
        int weight() { return height()*2.77; }
    
        void nextPerson()
        {
            curHeight=random(1, 24, 60);
        }
    };
    
    // ... inside the main ...
    RandomPersonGenerator rpg;
    while (n <= 10)
    { 
        rpg.nextPerson();
        cout << rpg.height() << " and " << rpg.weight() << endl;
        ++n;
    }
    
    Run Code Online (Sandbox Code Playgroud)

(顺便说一句,int main不是void main,而且for周期比while这种情况更合适)