编得太垃圾了,实在是不会用递归,麻烦帮忙指点一下错误

来源:百度知道 编辑:UC知道 时间:2024/05/07 23:56:24
#include "stdio.h"
int MD(a[],int n)
{
int f,m,i,count[i];
if(n==0)
f=0;
for(i=0;i<n;i++)
{
if(a[i]>0)
count[i]=1;
if(a[i]<0)
count[i]=-1;
if(a[i]==0)
count[i]=0;
}
f=count[n-1]+MD(a[],n-1);
return(f);
}
main()
{
int a[10],i;
for(i=0;i<10;i++)
scanf("%d",&a[i]);
printf("%d",MD(a,10));
}

你是想统计正数比负数多几个吧。
应该在if(n==0) f=0;之后加一个else,否则程序将会永远执行f=count[n-1]+MD(a[],n-1); 即使n已经变成了负数。
所以程序可以改成这样:
#include "stdio.h"
int MD(int a[],int n)
{
int f,m,i,count[n];
if(n==0) f=0;
else {
for(i=0;i<n;i++)
{
if(a[i]>0) count[i]=1;
if(a[i]<0) count[i]=-1;
if(a[i]==0) count[i]=0;
}
f=count[n-1]+MD(a,n-1);
}
return(f);
}

main()
{
int a[10],i;
for(i=0;i<10;i++)
scanf("%d",&a[i]);
printf("%d\n",MD(a,10));
}

或者更简单点,根本不需要一个count数组,因为每次只需要知道count[n-1]是几就行了。

所以可以改成如下:
#include "stdio.h"
int MD(int a[],int n)
{
int f;
if(n<=0) return 0;
else {
if(a[n-1]>0) f=1;
else if(a[n-1]<0) f=-1;
else f=0;