I'm making program where user enters numbers and program will find MAX and MIN + position of these numbers. I want to give the user a choice for the program to fill in the numbers for him using rand(). It's working almost perfect, program will find the MAX number with the position but the problem occurs when printing MIN number with position - always prints number 8 and position 1. Where is the problem? Finding MAX number is working but program cannot find MIN number. I just can't find the solution for this problem. Thank you for your help đ Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct elementposition
{
int min;
int max;
int positionMax;
int positionMin;
}elementposition;
int main()
{
struct elementposition minmax;
srand(time(NULL));
int a[500], i;
int c = sizeof(a) / sizeof(a[0]);
char y;
printf("How many numbers you want to enter: ");
scanf("%d", &c);
minmax.positionMax=minmax.positionMin = 0;
printf("Want to fill with random numbers? (Y/N)");
scanf(" %c",&y);
if(y == 'Y'||y == 'y')
{
for(i = 0; i < c; i++)
{
a[i] = rand() % 10000 + 1;
if(minmax.max < a[i])
{
minmax.max = a[i];
minmax.positionMax = i;
}
if(minmax.min > a[i])
{
minmax.min = a[i];
minmax.positionMin = i;
}
}
for(i = 0; i < c; i++)
{
printf("Number #%d: %d\n", i + 1, a[i]);
}
}
else
{
printf("------------------------------------ \n");
printf("Enter (%d) numbers: \n", c);
scanf("%d",&a[0]);
minmax.max = minmax.min = a[0];
for(i = 1; i < c; i++)
{
scanf("%d", &a[i]);
if(minmax.max < a[i])
{
minmax.max = a[i];
minmax.positionMax = i;
}
if(minmax.min > a[i])
{
minmax.min = a[i];
minmax.positionMin = i;
}
}
}
printf("\nMax number is %d, number position %d. \n", minmax.max, minmax.positionMax+1);
printf("Min number is %d, number position %d. \n", minmax.min, minmax.positionMin+1);
printf("------------------------------------ \n");
getch();
return 0;
}
Aucun commentaire:
Enregistrer un commentaire