Relatively new to C++ and this has been bugging me for a while. I’m trying to write a program that will do different things depending on what random number is generated.
To explain what I’m trying to do simply, lets pretend I’m creating a list of athletes and start by randomly generating their heights within a certain range. Easy to do no problem. Say then I want to generate their weight, based on their height. This is where things get messy. For some reason I can’t figure out, the program is randomly generating the weight based on a different height than the one it returns in the first place. I just don’t get it.
Anyway, here is a piece of (very simplified) sample code that hopefully shows what I’m trying to do. I’m sure I’m missing something obvious but I just can’t seem to figure it out.
#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;
}
It’s quite easy. You call
height()in yourweight()function. That means you’re getting a new random value for theheight. What you have to do is to modify yourweight()so that it can pass through a height parameter and calculate the weight based on it (and not on a new random value).Your new
height()function would look as follow:In your
main():