I began to write a code that displays even or odd numbers from random numbers. Write a program that tests the validity of the rand() function. Generate 10,000 random numbers. For each random number, determine if it is even (divisible by 2) or odd, counting the total number of even and odd numbers. Compute the ratio of even to odd numbers. Print to the screen the number of even numbers generated, the number of odd numbers generated and the ratio of even to odd numbers.
What should the ratio be if rand() is functioning properly? How does your result compare?
Code:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main(){
int hold;
srand(time(0));
hold=rand() %10000 +1;
cout <<hold;
// determine if integer is even or odd
if ( integer % 2== 0 )
// if the integer when divided by 2 has no remainder then it's even.
#include <iostream>
#include <ctime>
#include <cstdlib>
int main()
{
std::srand( std::time(nullptr) ) ;
constint N = 10000 ; // number of random numbers to be generated
int cnt_even_nums = 0 ;
// generate N random numbers
for( int i = 0 ; i < N ; ++i ) // loop N times
{
// each time through the loop:
constint r = std::rand() ; // generate a random number
// For each random number, determine if it is even (divisible by 2)
// or odd, counting the total number of even and odd numbers.
// note that by definition, zero is an even number
if( r%2 == 0 ) ++cnt_even_nums ;
}
// Print to the screen the number of even numbers generated,
// the number of odd numbers generated and the ratio of even to odd numbers.
constint cnt_odd_nums = N - cnt_even_nums ; // numbers that are not even are odd
std::cout << "number of even numbers generated: " << cnt_even_nums << '\n'
<< "number of odd numbers generated: " << cnt_odd_nums << '\n'
<< " ratio of even to odd numbers: " << double(cnt_even_nums) / cnt_odd_nums << '\n' ;
// convert to double to avoid integer division
}