范围内的奇数随机数[1..99]

时间:2016-10-31 18:40:10

标签: c++ random

我想用[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();
}

当我使用此代码时,我会收到:

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

这有什么问题?为什么有很多“0”?

2 个答案:

答案 0 :(得分:4)

为什么不应该?你只填写奇数:

    if (number%2!=0)
        a[i]=number;

如果随机数是偶数,请跳过将其添加到数组中。所以......你得到的0代表一个偶数。

答案 1 :(得分:0)

尝试这样的事情,而不是只有在实际得到奇数时才增加。

    #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; ) {
            number=(rand()%100)+1;
            if (number%2!=0)
          {
                a[i]=number;
            i++;
          }
        }
        print();
    }
相关问题