lundi 31 octobre 2016

Odd random number in range [1..99]

I want to fill an array with odd random numbers in a range [1..99].

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

const int N = 100;
int a[N];

void print(){
    for (int i=0; i<N; i++) 
        cout << a[i] << " ";
}

int main(){
    srand(time(NULL));
    int number;
    for (int i=0; i<N; i++) {
        number=(rand()%100)+1;
        if (number%2!=0)
            a[i]=number;
    }
    print();
}

When I use this code I receive:

0 7 0 0 29 0 0 93 0 0 29 0 27 0 0 13 35 0 0 0 0 0 51 0 0 0 97 99 15 73 79 0 73 0 21 39 0 7 25 41 1 99 31 0 0 1 0 81 69 73 37 95 0 0 0 41 21 75 97 31 0 0 0 0 0 0 31 21 0 11 33 65 0 69 0 0 9 63 27 0 13 0 63 27 0 7 0 0 99 0 77 0 59 5 0 99 0 69 0 0

What is wrong with that? Why there are a lot of "0"?




Aucun commentaire:

Enregistrer un commentaire