gpt4 book ai didi

C 程序比较两个大小不等的数组

转载 作者:行者123 更新时间:2023-11-30 14:33:05 25 4
gpt4 key购买 nike

我编写了一个程序来比较两个不同大小的数组,程序应该比较数组并返回第一个数组的索引,其中第一个数组的起始位置相等,但是由于某些语法或逻辑问题,程序无法正常工作。所以请参阅代码并告诉我问题出在哪里。谢谢。

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

int subArray( int first[], int size1, int second[], int size2)
{

int key = second [0] ; //init key of first element in second array
int i;
int y;
int found,count;


for (i = 0 ;size1 < i; i++)
{
if (first[i] == key)
count ++;
found = 1;
}

if (found== 1) // should compare first and second array and return -1 if not equal
{
for (y = 0 ;size2 < y; y++)
{
if (first[i] != second[y])

result =-1;
else
{
i++;

}

}


return result=count; //return index of first array where equal startring
}


int main()

{

int result;
int sizeArr1;
int sizeArr2;
int arr1[40]={0};
int arr2[40]={0};
// taking input and storing it in first array
scanf_s("%d", &sizeArr1);
for(int i = 0; i < sizeArr1; ++i)
{
scanf_s("%d", &arr1[i]);

}
// taking input and storing it in second array
scanf_s("%d", &sizeArr2);
for(int i = 0; i < 5; ++i)
{
scanf_s("%d", &arr2[i]);

}
result = subArray(arr1,sizeArr1,arr2,sizeArr2);
printf("%d",result);
}

最佳答案

你似乎忘记了阻止:

for (i = 0; size1 < i; i++) 
{
if (first[i] == key)
{
count++;
found = 1;
}
}

在您的原始代码中,found 将在每次 for 循环迭代中设置为 1,而不依赖于 if情况。

注意:您的代码格式非常糟糕,代码缩进和空白(空)行完全是随机的。仅此而已。

关于C 程序比较两个大小不等的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59505001/

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