Passing random numbers into a loop

Hey guys, wondering if someone can help me out here. Not that experienced with this yet!

I'm trying to pass multiple sets of two random numbers to a function and perform the same equation on each set, returning an integer, but so far I can only pass one random set, it doesn't rerun the function with a new numbers each time. Here is my code so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

#include <iostream>
#include <ctime>
using namespace std;

int functionOne(int a, int b);
int randomInt(const int from, const int to);

int main()
{
    int a, b;
    srand(time(NULL));

    a = randomInt(1, 198); //range -99 to 99
    b = randomInt(1, 198);

    functionOne(a, b);
    return EXIT_SUCCESS;
}

int functionOne(int a, int b)
{
    for(int totalCount = 0; totalCount < 10; ++totalCount)
    {
        if(a < b)
        {
            cout << "match ";
        }
        else
        {
            cout << "no match ";
        }
        
    }
    return EXIT_SUCCESS;
}

int randomInt(const int from, const int to)
{
	return rand() % (to + from) - (to / 2);
}


The idea is to pass 10 sets of integers to the algorithm and have it display match or no match.. Ultimately trying to make the following program: generate 1000 pairs of random coordinates of a line segment and a midpoint/radius of a circle, determine the percentage of lines that fall within the circle, and keep repeating the 1000 pair function until the percentage is greater than the previous pass.

but so far I can only pass one random set, it doesn't rerun the function with a new numbers each time

This is because you only pass one pair of parameters to functionOne() and re-use those parameters 10 times.

You could either call randomInt() inside the for loop and assign new values to a and b
OR
Move the for loop to main() and have it call randomInt() and functionOne().

1
2
3
4
5
6
7
8
9
10
11
int functionOne(/*int a, int b*/)
{
    for(int totalCount = 0; totalCount < 10; ++totalCount)
    {
    	int a = randomInt( 1, 198 );
    	int b = randomInt( 1, 198 );
    	/*
		. . .
    	*/
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
int main( )
{
	/*
	. . .
	*/
	for( int i{}; i < 10; i++ ) {
    	a = randomInt(1, 198); //range -99 to 99
    	b = randomInt(1, 198);

    	functionOne(a, b);
	}
}
Last edited on
Topic archived. No new replies allowed.