【发布时间】:2016-10-31 18:40:09
【问题描述】:
我想用 [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”?
【问题讨论】:
-
调试器是解决此类问题的正确工具。 在询问 Stack Overflow 之前,您应该逐行浏览您的代码。如需更多帮助,请阅读How to debug small programs (by Eric Lippert)。至少,您应该 [编辑] 您的问题,以包含一个重现您的问题的 Minimal, Complete, and Verifiable 示例,以及您在调试器中所做的观察。
-
提示:当随机数为偶数时不要增加
i。