简体   繁体   English

在数组问题中查找偶数(C ++)

[英]finding even numbers in the array issue (C++)

My code is to extract odd number and even number in an 1D array. 我的代码是提取一维数组中的奇数和偶数。

#include <iostream>
using namespace std;

int main() {
    int a[6] = {1,6,3,8,5,10};
    int odd[]={};
    int even[]={};

    for (int i=0; i < 6; i++) {
        cin >> a[i];
    }

    for (int i=0; i < 6; i++) {
        if (a[i] % 2 == 1) {
            odd[i] = a[i];
            cout << odd[i] << endl;
        }
    }

    cout << " " << endl;

    for (int i=0; i < 6; i++) {
        if (a[i] % 2 == 0) {
            even[i] = a[i];
            cout << even[i] << endl;
        }
    }

    return 0;
}

the output is: 输出为:

1
3
5

2
1
6

It shows that it successfully extract odd numbers but the same method applied to the even number. 它表明已成功提取了奇数,但对偶数应用了相同的方法。 It comes with an issue while the even number is 4. 偶数为4时会出现问题。

Could anyone help me find the cause here? 有人可以帮我在这里找到原因吗? Thanks. 谢谢。

You've got an Undefined Behavior, so result may be any, even random, even formatted hard drive. 您有未定义的行为,因此结果可能是任何硬盘,甚至是随机硬盘,甚至是格式化的硬盘。

int odd[] = {} is the same as int odd[/*count of elements inside {}*/] = {/*nothing*/} , so it's int odd[0]; int odd[] = {}int odd[/*count of elements inside {}*/] = {/*nothing*/}相同,因此它是int odd[0];

Result is not defined when you're accessing elements besides the end of array. 当您访问数组末尾以外的元素时,未定义结果。 You probably have to think about correct odd/even arrays size, or use another auto-sizeable data structure. 您可能必须考虑正确的奇/偶数组大小,或使用其他可自动调整大小的数据结构。

First, although not causing a problem, you initialize an array with data and then overwrite it. 首先,尽管不会造成问题,但是您可以使用数据初始化数组,然后将其覆盖。 The code 编码

int a[6] = {1,6,3,8,5,10};

can be replaced with 可以替换为

int a[6];

Also, as stated in the comments, 另外,如评论中所述,

int odd[]={};

isn't valid. 无效。 You should either allocate a buffer as big as the main buffer (6 ints) or use a vector (although I personally prefer c-style arrays for small sizes, because they avoid heap allocations and extra complexity). 您应该分配一个与主缓冲区一样大的缓冲区(6个整数),或者使用一个向量(尽管我个人更喜欢c样式的数组用于较小的大小,因为它们避免了堆分配和额外的复杂性)。 With the full-size buffer technique, you need a value like -1 (assuming you intend to only input positive numbers) to store after the list of values in the arrays to tell your output code to stop reading, or store the sizes somewhere. 使用全尺寸缓冲区技术时,您需要一个类似于-1的值(假设您只打算输入正数)存储在数组中的值列表之后,以告诉您的输出代码停止读取或将尺寸存储在某个位置。 This is to prevent reading values that haven't been set. 这是为了防止读取尚未设置的值。

I don't understand your problem when 4 is in the input. 输入4时,我不明白您的问题。 Your code looks fine except for your arrays. 除了数组之外,您的代码看起来还不错。

You can use std::vector< int > odd; 您可以使用std::vector< int > odd; and then call only odd.push_back(elem) whem elem is odd. 然后仅调用odd.push_back(elem)elem是奇数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM