gpt4 book ai didi

c - 动态数组 : Separating Numbers into Even and Odd Using C

转载 作者:太空宇宙 更新时间:2023-11-04 04:11:55 24 4
gpt4 key购买 nike

我的程序应该首先询问要读取的整数数量,然后动态分配一个刚好足以容纳我读取的值数量的数组。然后,我需要将这些值分为奇数和偶数。

这是我试过的代码

#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;
}

无论我输入什么,输出都只显示0。例如:

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

请帮我解决这个问题。提前致谢!

最佳答案

在获取用户输入时,尝试在变量名称前放置一个“&”符号。我认为这应该有效。

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

快乐编码:)

关于c - 动态数组 : Separating Numbers into Even and Odd Using C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56248851/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com