简体   繁体   中英

C - Getting the min and max of the randomly generated numbers

My code is below, this is my first programming course so expect a possibly stupid mistake.

Basically I am trying to get the min/max and the position number of them. However, my max works correctly up until 6 numbers are generated and I can't seem to understand why.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
  int n, r, x, i;
  int max, min;
  int num[0];

  printf("Enter an integer");
  scanf("%d", &n);

  x = n;

printf("\n Pos | Val");
for(n=0; n<x; n++)
{
    r = ( rand()%1000 ) + 1;
    printf("\n %3d | %3d", n+1, r);
}

  max=num[0];
    i=0;

    while(i<x) // while loop determing the biggest number
    {
        if(num[i]>max)
        {
    max=num[i];
        }
        i++;
}   

  printf("\nMax : %d",max); // biggest number
  return 0;
}

There are actually several places that needs improvement in your code.

Firstly, it is invalid to declare an array of size 0 in your code int num[0]; , so I'm not sure why your code work with a n up to 6.

Secondly, as you may learn very soon, indentation is very important while programming so that the code is better to understand and maintain in the future. Furthermore, while C is not a language that requires indentation (and that is considered one of its strengths) many common languages such as Python that rely on whitespace to differentiate functions do need careful management of indentation.

Third, RAND_MAX is not a multiple of 1000 so you would not obtain equal probability in your program. A srand function call is also recommended.

A possible implementation of your intended program (still ugly):

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAXN 1000
int main(void) {
    int n, r, i;
    int pos = 0;
    int max;
    int num[MAXN];

    printf("Enter an integer");
    scanf("%d", &n);
    srand(time(0));

    printf("\n Pos | Val");
    for (i = 0; i<n; i++)
    {
        r = (int)(((double)rand() / (RAND_MAX + 1)) * 1000) + 1;
        printf("\n %3d | %3d", i + 1, r);
        num[i] = r;
    }

    max = num[0];
    i = 0;
    for (i = 1; i < n; i++)
    {
        if (num[i] > max)
        {
            max = num[i];
            pos = i;
        }
    }

    printf("\nMax : %d | Pos : %d", max, pos); // biggest number
    //while (1);
    return 0;
}

As far as my tests, this piece works well

As already identified by numerous answers and comments, your primary problem is your array. Standard C doesn't allow array sizes of zero. GCC does unless you tell it to complain.

However, all the other answers continue to blithely use the array. For the problem stated, there's no need for an array at all. Also, the question text mentions 'minimum' as well as 'maximum', and 'position' as well as 'value' — though the code shown reports neither minimum nor position. Clearly, if this is just a preliminary phase before using the data for some other work, then you probably do need to save the data in an array. You can then decide whether to use a C99 (or later) VLA — variable length array — or whether to use dynamic memory allocation with malloc() et al, remembering to free the allocated space with free() .

Here's a simple revised program that doesn't use an array and does manage minimum and maximum as well as reporting positions. It deliberately changes the range of values to 0..999 so that there are never 4-digit numbers to throw the presentation off. You can decide what to do if you absolutely must used 1-based counting and values in the range 1..1000. (Using + 1 in selected locations is one part of the answer; deciding to replace %3d with either %d or %4d is probably the rest of the answer).

This code uses the time as a seed value for the random numbers, and it reports that seed value. If the program was going to be used seriously, I'd make it accept optional arguments, one of which would be the seed, so that previous runs can be recreated. I'd probably make it accept an argument for the number of random values to be generated too.

The code validates that a number was entered and validates that the number falls in the range 1..999, bailing out with an error message written to standard error if the value is not acceptable. Note that the error message diagnoses what is valid — there is nothing more frustrating than to be told that something is invalid but not why and what you need to do to fix it (and often, it helps to show what the program read — it might not be what the user thought the program would read).

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
    int n;
    printf("Enter number of random values to test: ");
    if (scanf("%d", &n) != 1 || n <= 0 || n >= 1000)
    {
        fprintf(stderr, "Didn't read a valid number in the range 1..999\n");
        return 1;
    }
    unsigned seed = time(0);
    srand(seed);
    printf("Seed: %u\n", seed);

    int minval = 0;
    int maxval = 0;
    int minidx = 0;
    int maxidx = 0;
    printf("\n Pos | Val\n");
    for (int i = 0; i < n; i++)
    {
        int r = (rand() % 1000);
        printf(" %3d | %3d\n", i, r);
        if (i == 0)
        {
            minval = r;
            maxval = r;
            minidx = i;
            maxidx = i;
        }
        else if (r > maxval)
        {
            maxval = r;
            maxidx = i;
        }
        else if (r < minval)
        {
            minval = r;
            minidx = i;
        }
    }

    printf("Minimum value was %3d at index %3d\n", minval, minidx);
    printf("Maximum value was %3d at index %3d\n", maxval, maxidx);

    return 0;
}

Example run (program mnmx67 compiled from mnmx67.c ):

$ mnmx67
Enter number of random values to test: 10
Seed: 1503763592

 Pos | Val
   0 | 201
   1 | 216
   2 |  85
   3 | 793
   4 | 382
   5 | 780
   6 | 341
   7 | 661
   8 |  75
   9 | 266
Minimum value was  75 at index   8
Maximum value was 793 at index   3
$

You did not store your random numbers in num, also You need to have some space to store these numbers. Try this for size, i commented my changes

#include <stdio.h>
#include <stdlib.h>

int main(void) {
  int n, r, x, i;
  int max, min;
  int * num;    // ++++++++ pointer to array

  printf("Enter an integer");
  scanf("%d", &n);

  x = n;
  num = malloc(x * sizeof(int));    // ++++++++++ allocate memory

printf("\n Pos | Val");
for(n=0; n<x; n++)
{
    r = ( rand()%1000 ) + 1;
    printf("\n %3d | %3d", n+1, r);
    num[n] = r;     // +++++++++  store your number
}

  max=num[0];
    i=0;

    while(i<x) // while loop determing the biggest number
    {
        if(num[i]>max)
        {
    max=num[i];
        }
        i++;
}   

  printf("\nMax : %d",max); // biggest number
  free(num);    // +++++++++ free memory

  return 0;
}

Your first mistake is that the array's dimension is zero. You need to set a size for the array.

I would do this by splitting the code into three additional functions: one to generate the numbers, and two others to find the min and max.

int *gennums(size_t n)
{
    int *nums;
    size_t i;

    if ((nums = malloc(n * sizeof (int))) != NULL) {
        for (i = 0; i < n; ++i)
            nums[i] = rand() % 1000;

        return nums;    // caller must free
    }
    return NULL;
}

int min(const int *arr, size_t n)
{
    assert(n > 0);
    int m = arr[0];
    size_t i;

    for (i = 0; i < n; ++i)
        if (arr[i] < m)
            m = arr[i];

    return m;
}

int max(const int *arr, size_t n)
{
    assert(n > 0);
    int m = arr[0];
    size_t i;

    for (i = 0; i < n; ++i)
        if (arr[i] > m)
            m = arr[i];

    return m;
}

Here int num[0];

You are not storing your random numbers in this array.Searching in that is meaning less.

Also size of your array should be at-least equal to n

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM