算法一样,结果却不同?
大家帮帮忙看看这俩个用分治法查找最大值与最小值的:第一个调用了函数Compriosn;第二个没有;
/*第一个*/
#include "stdafx.h"
#include "stdio.h"
#include "math.h"
#include "stdlib.h"
#define MAXQSIZE 100
/*调试用的变量,防止进入死循环*/
static long int tmp=1;
int A[MAXQSIZE];
int Compriosn ( int p, int q )
{
if ( p > q )
return p;
else
return q;
}
void REC_MAXMIN ( int i, int j, int *max, int *min )
{
int mid;
int gmax;
int gmin;
int hmax;
int hmin;
/*输出调试信息*/
printf("enter the maxmin()! [%d]tmes!\n",tmp);
tmp++;
/*如果调用此函数超过100次则退出程序*/
if ( tmp >= MAXQSIZE )
{
printf("The program mabye dead!\n");
exit(0);
}
if ( i == j )
{
printf("the i=j\n");
*max = A[i];
*min = A[i];
return;
}
if ( i == j - 1 )
{
printf("the i = j-1\n");
if ( A[i] > A[j] )
{
*max = A[i];
*min = A[j];
return;
}
else
{
*max = A[j];
*min = A[i];
return;
}
}
else
{
printf ("the i!=j and i!=j-1\n");
mid = ( i + j ) / 2;
REC_MAXMIN ( i, mid, &gmax, &gmin );
REC_MAXMIN ( mid + 1, j, &hmax, &hmin );
*max = Compriosn ( gmax, hmax );
*min = Compriosn ( gmin, hmin );
}
}
void main()
{
int i;
int n;
int max;
int min;
printf("请输入需要输入数字的个数n == >");
scanf("%d",&n);
printf("\n");
printf("请输入数列:\n");
for ( i = 0; i < n; i++ )
scanf("%d",&A[i]);
REC_MAXMIN ( 0, n - 1, &max, &min );
printf("结果:\n");
printf("max == %d\n",max);
printf("min == %d\n",min);
}
/*第二个*/
// 找最大值与最小值.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "stdio.h"
#include "math.h"
#include "stdlib.h"
#define MAXQSIZE 100
/*调试用的变量,防止进入死循环*/
static long int tmp=1;
int A[MAXQSIZE];
void REC_MAXMIN ( int i, int j, int *max, int *min )
{
int mid;
int gmax;
int gmin;
int hmax;
int hmin;
/*输出调试信息*/
printf("enter the maxmin()! [%d]tmes!\n",tmp);
tmp++;
/*如果调用此函数超过100次则退出程序*/
if ( tmp >= MAXQSIZE )
{
printf("The program mabye dead!\n");
exit(0);
}
if ( i == j )
{
printf("the i=j\n");
*max = A[i];
*min = A[i];
return;
}
if ( i == j - 1 )
{
printf("the i = j-1\n");
if ( A[i] > A[j] )
{
*max = A[i];
*min = A[j];
return;
}
else
{
*max = A[j];
*min = A[i];
return;
}
}
else
{
printf ("the i!=j and i!=j-1\n");
mid = ( i + j ) / 2;
REC_MAXMIN ( i, mid, &gmax, &gmin );
REC_MAXMIN ( mid + 1, j, &hmax, &hmin );
*max = gmax > hmax ? gmax : hmax;
*min = gmin < hmin ? gmin : hmin;
}
}
void main()
{
int i;
int n;
int max;
int min;
printf("请输入需要输入数字的个数n == >");
scanf("%d",&n);
printf("\n");
printf("请输入数列:\n");
for ( i = 0; i < n; i++ )
scanf("%d",&A[i]);
REC_MAXMIN ( 0, n - 1, &max, &min );
printf("结果:\n");
printf("max == %d\n",max);
printf("min == %d\n",min);
}
同样输入:
5 3 2 6 7 8 4 9
但第一个函数却是:
max == 9;
min == 7;
第二个函数是正确答案:
max == 9;
min == 2;
请问第一个函数为什么调用程序不成功呢????谢拉~