c++

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.

cout << integer << " is even "
<<endl;
else

// the integer is odd

cout << integer << " is odd "
<<endl;

return 0;
}
Your program does not yet
* generate 10'000 numbers as requested
* count odds and evens
* show counts
* show ratio of counts

Can you add those?

PS. Please use code thags when posting code. See http://www.cplusplus.com/articles/jEywvCM9/
I need help doing that part, can you show me how it's done? how would the code look like... thank you
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
#include <iostream>
#include <ctime>
#include <cstdlib>

int main()
{
    std::srand( std::time(nullptr) ) ;

    const int 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:

        const int 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.

    const int 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
}
Last edited on
Topic archived. No new replies allowed.