Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/148.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何确保数组具有偶数个元素_C++ - Fatal编程技术网

C++ 如何确保数组具有偶数个元素

C++ 如何确保数组具有偶数个元素,c++,C++,因此,我使用rand()在数组中生成一个随机数字字符串。但是,我只希望生成偶数个数字。示例:675986(生成6位数字)或56237946(生成8位数字) 这是到目前为止我的代码 #include <iostream> #include <cstdlib> #include <ctime> using namespace std; const int MAX = 30; void constructArray(char[], int); void pr

因此,我使用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;
}
#包括
#包括
#包括
使用名称空间std;
常数int MAX=30;
void数组(char[],int);
void printary(常量字符[],int);
int main()
{
字符str[MAX];
int n;
srand(时间(空));
n=rand()%20+4;
构造数组(str,n);
打印阵列(str,n);
}
void构造函数数组(字符str[],int n)
{
字符数字[]={'1','2','3','4','5','6','7','8','9','0'};
int k;
对于(int i=0;imain()

n = rand() % 20 + 4;
要检查它是否是偶数,只需执行
!(n&1)
。然后,如果它是奇数,您可以将其减量。或者,您也可以直接转到
(~1&n)
,将您的数字转换为偶数

其他解释:


这可以使用。它检查是否设置了最低有效位,当且仅当数字为奇数时才为真。替代方法重置最低有效位,确保数字为偶数。它将正奇数转换为最接近的较小偶数,以便它将保持在当前的上限24下。

为什么不使用整数除法对您有利:

n = rand() % 20 + 4;
n = n / 2;
n = n * 2;
或者你可以检查一下这是否奇怪:


如果(n%2!=0)n=n+1;
字符ch='0'+2*(rand()%5)
?我不知道这是否有趣,但原始数字在4到23之间。对于23,您将增加超过这些边界,如果MAX似乎被定义为24,这可能是一个问题。
rand()%10*2+4
?@MooingDuck:-)是的,这更简单!但OP可以保留我的答案,以防他对数字控制能力较弱(例如,
cin>>n;
);-)