简体   繁体   English

动态数组:使用C将数字分为偶数和奇数

[英]Dynamic Array: Separating Numbers into Even and Odd Using C

My program should first ask for the number of integers to read and dynamically allocate an array just big enough to hold the number of values I read. 我的程序首先应要求读取整数的数量,并动态分配一个恰好足以容纳我读取的值数量的数组。 Then, I need to categorize these values into odd and even. 然后,我需要将这些值分为奇数和偶数。

This is the code I've tried 这是我尝试过的代码

#include <stdio.h> 
#include <stdlib.h>
int main(void){

//declare variables
int i; //loop counter
int count; //integer amount from user
int j = 0; int k = 0;

// read in integer count from user
printf("enter the amount of numbers: ");
scanf("%d", &count);

// declare pointer 
int *number = malloc(sizeof(int)*count);
int *evens = malloc(sizeof(int)*count);
int *odds = malloc(sizeof(int)*count);

// declare variable
//int odds_count = 0;
//int evens_count = 0;

//loop to read in numbers from user
for (i=0; i<count; i++){
    printf("enter number %02d: ",i+1);
    scanf("%d",(number+i));
    printf("you entered %d\n", *(number+i)); //--- entered values are correct here
    if (*(number+i)% 2 ==0){
        *(number+i) = *(evens+j);
        j++;
        //evens_count++;
    } else {
        *(number+i) = *(odds+k);
        k++;
    }
    printf("you entered %d\n", *(number+i));  //---entered values become 0
}
//print array elements
printf("\nEntered array elements are:\n");
for(i=count;i>0;i--)
{
    printf("%d ",*(number+i));
}
printf("\n");

// print out even numbers
printf("even numbers: ");
for (i=0;i<j;i++){
    printf("%5d",*(evens+i));
}
printf("\n");

// print out odd numbers
printf("odd numbers: ");
for (i=0;i<k;i++){
    printf("%5d",*(odds+i));
}
printf("\n");

return 0;
}

No matter what input I enter, the output only displays 0. Eg: 无论我输入什么输入,输出都只会显示0。例如:

Input- 1, 2, 3
Output-
Evens: 0
Odds: 0 0

Please help me with this. 请帮我解决一下这个。 Thanks in advance! 提前致谢!

While getting the input from user, try putting an '&' symbol before your variable name. 从用户那里获取输入时,请尝试在变量名前添加一个'&'符号。 I think that should work. 我认为应该可以。

scanf("%d",&(number+i));

Happy coding :) 快乐的编码:)

Your biggest issues regarding assigning values occurs when you attempt to assign evens[j] and odds[j] to numbers[i] before the elements of either evens or odds have been initialized. 有关分配值的最大问题发生在尝试在evensodds的元素初始化之前将evens[j]odds[j]分配给numbers[i] Following your call to malloc for each evens and odds the block of memory allocated contains whatever garbage values happen to be in that memory region at the time of allocation. 在为每个evensodds调用malloc之后,分配的内存块包含分配时恰好在该内存区域中的所有垃圾值。 malloc does not initialize the content of the memory in any way and leave the values indeterminate. malloc不会以任何方式初始化内存的内容并使值不确定。 If you want to both allocate and zero all bytes, you can use calloc instead of malloc . 如果要同时分配所有字节并将其设置为零,则可以使用calloc代替malloc

This problem occurs here: 在这里发生此问题:

    if (*(number+i)% 2 ==0){
        *(number+i) = *(evens+j);
        j++;
        //evens_count++;
    } else {
        *(number+i) = *(odds+k);
        k++;
    }

Look carefully, you check whether numbers[i] is even/odd with % 2 == 0 , but then attempt to overwrite the value at numbers[i] with either evens[j] or odds[k] -- this is backwards . 仔细查看,您检查numbers[i]是否为% 2 == 0偶数/奇数,但是尝试使用偶数evens[j]odds[k]覆盖numbers[i]的值- 这是向后的 The intent would be to assign the value in numbers[i] to either evens[j] or odds[k] , eg 目的是将numbers[i]的值分配给evens[j]odds[k] ,例如

    if (number[i] % 2 ==0){
        evens[j] = number[i];
        j++;
        //evens_count++;
    } else {
        odds[k] = number[i];
        k++;
    }

Next, your use of variables is jumbled. 接下来,您对变量的使用变得混乱。 You don't need all the different i, j, k counters declared at the beginning of main() . 您不需要在main()开头声明的所有不同的i, j, k计数器。 For the past 20 years, since C99, you can declare the loop variable within the for loop declaration itself. 自C99以来的20年来,您可以在for循环声明本身中声明循环变量。 This eliminates the chance that your use of your loop variable will conflict with another use of i, j, k somewhere else in the program. 这消除了您对循环变量的使用与程序中其他位置的i, j, k其他使用冲突的可能性。

You have count, odd_count & even_count , those are the only counters you need. 您拥有count, odd_count & even_count这是您唯一需要的计数器。

Further, you need to VALIDATE every User Input and every Allocation. 此外,您需要验证每个用户输入和每个分配。 Otherwise, you risk invoking Undefined Behavior with the slip of a keystroke or when (not "if") an allocation returns NULL . 否则,您可能会击按键或在分配(如果不是“ if”)返回NULL时调用未定义行为 Validate every critical step. 验证每个关键步骤。

Putting those measures to use, you can simplify your declaration to: 利用这些措施,您可以将声明简化为:

    int count,          /* integer amount from user     */
        odd_count = 0,  /* odd count (initialized zero) */
        even_count = 0, /* even count (initialized zero)*/
        *number,        /* declare pointers             */
        *evens,
        *odds; 

You can validate your input with: 您可以使用以下命令验证您的输入:

    /* read in integer count from user (VALIDATE every input) */
    printf("enter the amount of numbers: ");
    if (scanf("%d", &count) != 1) {
        fputs ("error: invalid integer input.\n", stderr);
        return 1;
    }
    ...
    for (int i = 0; i < count; i++) {   /* loop count times for input */
        printf ("enter number %2d: ", i + 1);
        if (scanf ("%d", &number[i]) != 1) {    /* validate EVERY input */
            fputs ("error: invalid integer input.\n", stderr);
            return 1;
        }
        if (number[i] % 2 == 0)     /* assign, increment evens count */
            evens[even_count++] = number[i];
        else                        /* same for odds */
            odds[odd_count++] = number[i];
    }

And you can validate your allocations: 您可以验证您的分配:

    /* allocate count integers each pointer (VALIDATE every allocation) */
    if ((number = malloc (count * sizeof *number)) == NULL) {
        perror ("malloc-number");
        return 1;
    }
    if ((evens = malloc (count * sizeof *evens)) == NULL) {
        perror ("malloc-evens");
        return 1;
    }
    if ((odds = malloc (count * sizeof *odds)) == NULL) {
        perror ("malloc-odds");
        return 1;
    }

Then it is simply a matter of looping i = 0; i < count 那么,这只是循环i = 0; i < count i = 0; i < count to output the number , i = 0; i < even_count i = 0; i < count以输出numberi = 0; i < even_count i = 0; i < even_count to output evens and finally i = 0; i < odd_count i = 0; i < even_count输出evens和最后i = 0; i < odd_count i = 0; i < odd_count to output odds , eg i = 0; i < odd_count输出odds ,例如

    puts ("\n numbers\n--------");      /* output each array on its own */
    for (int i = 0; i < count; i++)
        printf ("%8d\n", number[i]);

    puts ("\n   evens\n--------");
    for (int i = 0; i < even_count; i++)
        printf ("%8d\n", evens[i]);

    puts ("\n    odds\n--------");
    for (int i = 0; i < odd_count; i++)
        printf ("%8d\n", odds[i]);

And Finally, you can output all 3 arrays at once with: 最后,您可以一次输出所有3个数组:

    /* output all arrays together */
    puts ("\nnumbers      even      odd\n-------- -------- --------");
    for (int i = 0; i < count; i++) {       /* loop printing number */
        printf ("%8d", number[i]);
        if (i < even_count) {               /* if i < even_count */
            printf (" %8d", evens[i]);      /* output evens */
            if (i < odd_count)              /* if odds too, output them */
                printf (" %8d\n", odds[i]);
            else
                putchar ('\n');             /* no more odds output '\n' */
        }
        else if (i < odd_count)             /* if only odds left, output */
            printf ("%18d\n", odds[i]);
        else
            putchar ('\n');
    }

At the end, don't forget to free the memory you allocate, eg 最后,不要忘记释放您分配的内存,例如

    free (number);  /* don't forget to free what you allocated */
    free (evens);
    free (odds);

Putting it altogether, you could do: 综上所述,您可以执行以下操作:

#include <stdio.h> 
#include <stdlib.h>

int main(void) {

    int count,          /* integer amount from user     */
        odd_count = 0,  /* odd count (initialized zero) */
        even_count = 0, /* even count (initialized zero)*/
        *number,        /* declare pointers             */
        *evens,
        *odds; 

    /* read in integer count from user (VALIDATE every input) */
    printf("enter the amount of numbers: ");
    if (scanf("%d", &count) != 1) {
        fputs ("error: invalid integer input.\n", stderr);
        return 1;
    }

    /* allocate count integers each pointer (VALIDATE every allocation) */
    if ((number = malloc (count * sizeof *number)) == NULL) {
        perror ("malloc-number");
        return 1;
    }
    if ((evens = malloc (count * sizeof *evens)) == NULL) {
        perror ("malloc-evens");
        return 1;
    }
    if ((odds = malloc (count * sizeof *odds)) == NULL) {
        perror ("malloc-odds");
        return 1;
    }

    for (int i = 0; i < count; i++) {   /* loop count times for input */
        printf ("enter number %2d: ", i + 1);
        if (scanf ("%d", &number[i]) != 1) {    /* validate EVERY input */
            fputs ("error: invalid integer input.\n", stderr);
            return 1;
        }
        if (number[i] % 2 == 0)     /* assign, increment evens count */
            evens[even_count++] = number[i];
        else                        /* same for odds */
            odds[odd_count++] = number[i];
    }

    puts ("\n numbers\n--------");      /* output each array on its own */
    for (int i = 0; i < count; i++)
        printf ("%8d\n", number[i]);

    puts ("\n   evens\n--------");
    for (int i = 0; i < even_count; i++)
        printf ("%8d\n", evens[i]);

    puts ("\n    odds\n--------");
    for (int i = 0; i < odd_count; i++)
        printf ("%8d\n", odds[i]);

    /* output all arrays together */
    puts ("\nnumbers      even      odd\n-------- -------- --------");
    for (int i = 0; i < count; i++) {       /* loop printing number */
        printf ("%8d", number[i]);
        if (i < even_count) {               /* if i < even_count */
            printf (" %8d", evens[i]);      /* output evens */
            if (i < odd_count)              /* if odds too, output them */
                printf (" %8d\n", odds[i]);
            else
                putchar ('\n');             /* no more odds output '\n' */
        }
        else if (i < odd_count)             /* if only odds left, output */
            printf ("%18d\n", odds[i]);
        else
            putchar ('\n');
    }

    free (number);  /* don't forget to free what you allocated */
    free (evens);
    free (odds);
}

Example Use/Output 使用/输出示例

$ ./bin/number_evens_odds
enter the amount of numbers: 10
enter number  1: 21
enter number  2: 22
enter number  3: 23
enter number  4: 24
enter number  5: 119
enter number  6: 121
enter number  7: 131
enter number  8: 140
enter number  9: 141
enter number 10: 143

 numbers
--------
      21
      22
      23
      24
     119
     121
     131
     140
     141
     143

   evens
--------
      22
      24
     140

    odds
--------
      21
      23
     119
     121
     131
     141
     143

numbers      even      odd
-------- -------- --------
      21       22       21
      22       24       23
      23      140      119
      24               121
     119               131
     121               141
     131               143
     140
     141
     143

Look things over and let me know if you have further questions. 仔细检查一下,如果您还有其他问题,请告诉我。

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

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