gpt4 book ai didi

c - 如何在 C 中正确比较和打印出此数组中的匹配元素?

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

我有一个简单的问题,我正在尝试用 C 编写解决方案。

If an array arr contains n elements, then write a program to check 
if arr[0] = arr[n-1], arr[1] = arr[n-2] and so on.

我的代码看起来像这样-

#include<stdio.h>
int main()
{
int arr[10],i=0,j;
int k=0;
printf("\n Enter 10 positive integers: \n");
for(k=0;k<=9;k++)
scanf("%d",&arr[k]);

while(i<=9)
{
for(j=9;j>=0;j--)
{
if(arr[i]==arr[j])
{
printf("\n The array element %d is equal to array element %d\n", arr[i],arr[j]);
}

i++;
continue;
}
}

return 0;
}

输入此输入时-

 Enter 10 positive integers:
10
20
30
40
50
60
40
80
20
90

我得到的输出是-

 The array element 20 is equal to array element 20

The array element 40 is equal to array element 40

The array element 40 is equal to array element 40

The array element 20 is equal to array element 20

现在,这段代码有两个问题-

  1. 如您所见,程序两次打印出匹配的数组元素。这是因为,按照我构建程序的方式,一旦变量 i 从第一个元素到最后一个元素循环遍历数组,然后 j 从最后一个元素循环遍历到第一个元素。因此每个都打印出匹配的数组元素一次,从而产生两组值。
  2. 我的第二个问题是——在我的代码中,我在 for 循环中对数组的长度进行了硬编码(对于 10 个元素的数组为 0 到 9)。可以做哪些更改,以便用户输入的数组长度可以直接用于 for 循环?

我读到过,在 C 中,数组维数(声明时)不能是变量。所以,像这样的声明(这是我的第一个想法)是行不通的-

int n; // n is no. of elements entered by the user

int arr[n];

我是编程新手,所以如果问题听起来/太简单、质量太差,我深表歉意。

谢谢。

最佳答案

1)你可以遍历数组一半,只得到一次打印。您可以使用 for(j=9;j>=9/2;j--) 而不是 for(j=9;j>=0;j--) >.

2)

int n;
int arr[n].

最近的编译器支持这个声明。如果你不喜欢使用它,你可以为数组进行动态内存分配。

关于c - 如何在 C 中正确比较和打印出此数组中的匹配元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24989486/

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