2016-11-04 64 views
1

所以我用一个rand()来产生一个数组中的随机数字串。但是,我只想要生成偶数个数字。例如:675986(生成6位数字)或56237946(生成8位数字)。如何确保一个数组有偶数个元素

这是到目前为止我的代码

#include <iostream> 
#include <cstdlib> 
#include <ctime> 
using namespace std; 

const int MAX = 30; 


void constructArray(char[], int); 

void printArray (const char[], int); 


int main() 
{ 
    char str [MAX]; 
    int n; 

    srand(time(NULL)); 

    n = rand() % 20 + 4; 

    constructArray(str, n); 
    printArray(str, n); 

} 

void constructArray(char str[], int n) 
{ 
    char digits [] = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'}; 

    int k; 




    for (int i = 0; i < n; i++) 
    {  
     k = rand() % 10; 
     str [i] = digits[k]; 



     if (str[0] == '0') 
     { 
      str[0] = digits[k] + 1; 
     } 

    } 

} 

void printArray (const char str [], int n) 
{ 
    cout << "Given "; 
    for (int i = 0; i < n; i++) 
     cout << str [i]; 
    cout << endl; 
} 
+1

'炭CH = '0' + 2 *(RAND()%5)'? –

回答

1

main()您确定的位数n

n = rand() % 20 + 4; 

要检查它是否是偶数,只是做!(n&1)。如果它很奇怪,那么你可以减少它。或者,您也可以直接转到(~1&n),它只是将您的号码转换为偶数。 Online demo

附加说明:

这个工程使用bit manipulation magics。它检查是否设置了最低有效位,当且仅当该数字是奇数时才为真。替代方案重置最不重要的位,确保编号是均匀的。它把在最近的小偶数正奇数,这样它会留在你目前的上限是24

+0

'rand()%10 * 2 + 4'? –

+0

@MooingDuck :-)是的,这更简单!但是OP可以保留我的答案,以防他有较少控制的数字(例如'cin >> n;');-) – Christophe

0

为什么不使用整数除法对您的好处:

n = rand() % 20 + 4; 
n = n/2; 
n = n * 2; 

或者你可以只检查如果是奇数:

if (n % 2 != 0) n = n + 1;

+0

我不知道它是否感兴趣,但原始数字在4到23之间。随着23,你会增加超出这些界限,如果MAX似乎被定义为24,这可能是一个问题。 – Christophe

相关问题