我有一个作业要编写一个递归程序,该程序获取一个数组(我们称之为 arr1)、数组的大小 (n) 和一个值。 程序将检查数组中是否有两个数字,以便它们的总和为 s。 例子 如果数组为 {1,3,2,0,5} 且 s=7,则该函数将打印“yes”,因为 5+2=7。 如果数组为 {1,3,2,0,5} 且 s=9,则该函数将打印“no”。没有任何一对的总和等于 9。
我的算法是这样工作的: 我计算数组中最后一个点(arr1[n-1])与其他每个点的摘要。如果我发现一对夫妇的总和是 s,那就太好了,打印 yes 并离开。 如果我没有找到,那么我会做同样的事情,但是我检查 arr1[n-2] 而不是 arr1[n-1]。我删除了最后一个位置。
这是我的代码:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void input_array_dyn(int* a, int n);
void rec(int* a,int n, int s);
void main()
{
int n=0,s=0;
int* a;
printf("Enter value S\n");
scanf("%d",&s);
printf("Enter the size of the array\n");
scanf("%d",&n);
a=(int*)calloc(n,sizeof(int));
printf("Enter %d values for the array\n",n);
input_array_dyn(a,n);
rec(a,n,s);
free(a);
getch();
}
void input_array_dyn(int* a,int n)
{
int i=0;
for(i=0;i<n;i++)
scanf("%d",a[i]);
}
void rec(int* a,int n, int s)
{
int i;
if(n==1)
{
printf("There are no 2 number whos summary yields S\n");
return;
}
for(i=0;i<n-1;i++)
{
if(a[n-1]+a[i]==s)
{
printf("There are two numbers that give s\n");
return;
}
}
rec(a,n-1,s);
}
我收到一条错误消息:“Test.exe 中 0x5846e30e (msvcr100d.dll) 处出现未处理的异常:0xC0000005:写入位置 0x00000000 时出现访问冲突。”
还有:有没有人有更好的算法来做到这一点? :)
最佳答案
在input_array_dyn()
中:
scanf("%d", a[i]);
您忘记了&
。
关于c - 检查 C 中数组的值时出现未处理的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14693486/