という問題です
次のプログラムの[void maxminRect]は自分で作りました。それ以外は例題をそのまま使っているので基本的には変えていません。(xmax,xmin,ymax,yminは付け足しました。)
最初の一回はきちんと動作を確認できたと思ったのですが、二回目以降は違う答えが返ってきてしまいます。何が違うのでしょうか?コメントで囲ってあるところが僕が付け足したところです。
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
typedef struct{
int LDx,LDy,RUx,RUy;
int width,height;
int area;
}Rectangle;
void genRect(Rectangle *,int);
void callRect(Rectangle *,int);
void dispRect(Rectangle);
}
//↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
void maxminRect(Rectangle *,int,int *,int *,int *,int *);
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
void main(void)
{
int i, n ,xmax, xmin, ymax, ymin;
Rectangle *rect;
srand(time(NULL));
n = -1;
while(n <= 0){
printf("長方形個数:");
scanf("%d",&n);
}
//長方形配列のメモリ
rect = (Rectangle *)malloc(n *sizeof(Rectangle));
genRect(rect,n); //長方形生成
callRect(rect,n); //各長方形の計算
for(i = 0;i < n;i++){
dispRect(rect[i]);
}
//↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
printf("\n\n");
maxminRect(rect,n,&xmax,&xmin,&ymax,&ymin);
printf("縦の最大値は%d,最小値は%d。横の最大値は%d、最小値は%d",ymax,ymin,xmax,xmin);
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
return;
}
void genRect(Rectangle*rect,int n)
{
int i;
for(i = 0;i<n;i++){
rect[i].LDx = rand()%(20+20+1)-20;
rect[i].LDy = rand()%(40-10+1)+10;
rect[i].RUx = rand()%(20+20+1)-20;
rect[i].RUy = rand()%(40-10+1)+10;
}
return;
}
void callRect(Rectangle *rect,int n)
{
int i,w,h,area;
for(i = 0;i < n;i++){
w = rect[i].RUx - rect[i].LDx;
if(w < 0) w = -w;
rect[i].width = w;
h = rect[i].RUy - rect[i].LDy;
if(h < 0) h = -h;
rect[i].height = h;
rect[i].area = w*h;
}
return;
}
void dispRect(Rectangle rect)
{
printf("(%4d,%4d)->(%4d,%4d)",rect.LDx,rect.LDy,rect.RUx,rect.RUy);
printf("Width = %3d,Height = %3d,",rect.width,rect.height);
printf("Area = %5d\n",rect.area);
return;
}
//↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
void maxminRect(Rectangle *rect,int n,int *xma,int *xmi,int *yma,int *ymi)
{
int i, j;
*xma = *xmi = rect[0].RUx;
*yma = *ymi = rect[0].RUy;
for(i = 0;i < n;i++){
for(j = i + 1;j < n;j++){
if(*xma < rect[i].RUx) *xma = rect[i].RUx;
if(*xma < rect[i].LDx) *xma = rect[i].LDx;
if(*xmi > rect[i].RUx) *xmi = rect[i].RUx;
if(*xmi > rect[i].LDx) *xmi = rect[i].LDx;
if(*yma < rect[i].RUy) *yma = rect[i].RUy;
if(*yma < rect[i].LDy) *ymi = rect[i].LDy;
if(*ymi > rect[i].RUy) *yma = rect[i].RUy;
if(*ymi > rect[i].LDy) *ymi = rect[i].LDy;
}
}
return;
}
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑