随机整数出现在程序错误

Random Integers Appearing In Program Bug

本文关键字:程序 错误 整数 随机      更新时间:2023-10-16

所以我试着编写一个程序,将一个整型数组分成两个,一个用于偶数整型,一个用于非偶数整型。现在,奇怪的是,如果我只在基本数组中输入偶数或非偶数,程序运行正常,但如果我输入两者的混合,两个新数组中保存的一个值将是一个随机的,通常是负数,大数,知道为什么吗?

#include <iostream>
using namespace std;
void main()
{
    int *a, n, *even_nums = 0, *uneven_nums = 0, counter_even = 0,counter_uneven = 0;
    cout << "How many values does your array have?n" << endl;
    cin >> n;
    a = new int[n];
    cout << "nEnter the values in your array:" << endl;
    for (int i = 0; i < n; i++)
    {
        cout << "a[" << i << "] = ";
        cin >> a[i];
        if (a[i] % 2 == 0)
            counter_even++;
        else 
            counter_uneven++;
    }
    if (counter_even == 0)
        cout << "There are no even numbers in your array." << endl;
    else
        even_nums = new int[counter_even];
    if (counter_uneven == 0)
        cout << "There are no uneven numbers in your array." << endl;
    else
        uneven_nums = new int[counter_uneven];
    for (int i = 0; i < n; i++)
    {
        if (a[i] % 2 == 0)
            even_nums[i] = a[i];
        else
            uneven_nums[i] = a[i];
    }
    if (counter_even != 0)
    {
        cout << "nThe even numbers in your array are:" << endl;
        for (int i = 0; i < counter_even; i++)
            cout << even_nums[i] << " ";
    }
    if (counter_uneven != 0)
    {
        cout << "nThe uneven numbers in your array are:" << endl;
        for (int i = 0; i < counter_uneven; i++)
            cout << uneven_nums[i] << " ";
    }
    system("PAUSE");
}

In

for (int i = 0; i < n; i++)
{
    if (a[i] % 2 == 0)
        even_nums[i] = a[i];
    else
        uneven_nums[i] = a[i];
}

对所有数组使用相同的索引。这将不起作用,因为even_numsuneven_nums将小于a,如果你有两个。你最终会写过数组的末尾,这是未定义的行为。

你需要做的是为每个数组添加一个索引,并且每次你向数组中插入一个元素时,你就会推进该索引。

for (int i = 0, u = 0, e = 0; i < n; i++)
{
    if (a[i] % 2 == 0)
        even_nums[e++] = a[i];
    else
        uneven_nums[u++] = a[i];
}

你也使用void main(),这是不标准的,不应该使用。int main()int main(int argc, char** argv)main()的标准可接受签名

for (int i = 0; i < n; i++)
{
    if (a[i] % 2 == 0)
        even_nums[i] = a[i];
    else
        uneven_nums[i] = a[i];
}

您正在使用i作为数组a, even_numsuneven_nums的相同索引。您需要为这些数组使用单独的索引。例如,如果您有n=10个元素,5个偶数和5个奇数,您的even_numsuneven_nums每个只包含5个元素。