gpt4 book ai didi

c - 这个使用 RECURSION 删除给定数组中所有强数字的函数有什么错误?

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

此处使用的所有其他函数(checkstrong 和 factorial)工作得很好。这个 deletestrong 函数最终会删除数组中的所有元素。

int deletestrong(int arr[],int n,int current){
if(current >= n){
return n;
}
if(checkstrong(arr[current]==1)){
if(current== n-1){
n--;
}

else {
for(int i=current; i< n-1 ;i++){
arr[i]=arr[i+1];
}
n--;
}
}

else{
current++;
}
deletestrong(arr,n,current);
}

驱动程序功能

int main(){
int n;
int arr[20];
printf("Enter number of elements.\n");
scanf("%d",&n);

printf("Enter the array.\n");
for(int i=0;i<n;i++){
scanf("%d",&arr[i]);
}
printarray(arr,n);
n=deletestrong(arr,n,0);
printf("After deleting all the strong numbers.\n");
printarray(arr,n);
}

最佳答案

对于初学者来说,第三个参数是多余的。该函数可以用不同的方式编写。一种方法是当函数返回数组中不是强数字的元素数时。

你的函数实现至少有未定义的行为,因为当控制传递给这个语句时函数不返回任何东西

    //...
deletestrong(arr,n,current);
}

这个if语句

 if( checkstrong( arr[current] == 1 ) ){

有一个逻辑错误。你的意思是相反

if( checkstrong( arr[current] ) == 1 ){

函数可以这样写

size_t deletestrong( int a[], size_t n )
{
size_t non_strong_numbers = 0;

if ( n )
{
if ( checkstrong( *a ) )
{
for ( size_t i = 1; i != n; i++ ) a[i-1] = a[i];
}
else
{
non_strong_numbers = 1;
++a;
}

non_strong_numbers += deletestrong( a, n - 1 );
}

return non_strong_numbers;
}

并称呼为

size_t n;
int arr[20];
printf("Enter number of elements.\n");
scanf( "%zu",&n );
//...
n = deletestrong( arr, n );
//...

关于c - 这个使用 RECURSION 删除给定数组中所有强数字的函数有什么错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58306014/

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