gpt4 book ai didi

c - 用于分配偶数和奇数的数组

转载 作者:行者123 更新时间:2023-11-30 20:58:04 24 4
gpt4 key购买 nike

我正在考虑一个数组来查找如何在两个连续的数组中分配偶数和奇数。

#include <stdio.h>
#include <math.h>

int main()
{
int a[100],odd[100],even[100],i,j,n;
for(i=0;i<=n;i++)
{
a[i]=0;
odd[i]=0;
even[i]=0;
}
printf("Enter the number of elements which you want to check as even or odd");
scanf("%d",&n);
for(i=0;i<n;i++)
{
if(a[i]%2==0)
a[i]=even[i];
else
a[i]=odd[i];
}
for(i=0;i<n;i++)
printf("The set of even numbers is %d"),even[i];
for(i=0;i<n;i++)
printf("The set of even numbers is %d"),odd[i];
return 0;
}

程序无法运行。我现在无法发现错误。任何人都可以发现错误吗?编译器显示出**段错误              

                               

                               

...程序已完成并退出

de 139                          

按 Enter 退出控制台。

**

最佳答案

我尝试通过注释指出代码中的一些错误。

而且我认为这段代码还有一个逻辑问题,就是你想将一个数字列表放入奇数数组和偶数数组,但偶数和奇数数组的初始值都为零。

当你将数字列表分成两个数组时,你并没有覆盖所有的初始值,这会导致最后打印一些零值,但它们不属于奇数也不属于偶数。

    #include <stdio.h>
#include <math.h>

int main()
{
int a[100],odd[100],even[100],i,j,n;
//you should first assign a vaule to n and then use n
//and be careful for the value of the n,
//it should not larger than the size of the array,or it will overflow.
for(i=0;i<=n;i++)
{
a[i]=0;
odd[i]=0;
even[i]=0;
}
//put below two lines to the front of the above for-loop
printf("Enter the number of elements which you want to check as even or odd");
scanf("%d",&n);
for(i=0;i<n;i++)
{
if(a[i]%2==0)
a[i]=even[i];
else
a[i]=odd[i];
}
for(i=0;i<n;i++)
//you type a wrong 'printf' satement,here is the right way
//printf("The set of even numbers is %d",even[i]);
printf("The set of even numbers is %d"),even[i];
for(i=0;i<n;i++)
printf("The set of even numbers is %d"),odd[i];//you type a wrong 'printf' satement
return 0;
}

关于c - 用于分配偶数和奇数的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54623303/

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