1

I got an assignment yesterday that goes as follows: Generate and show 20 random numbers in the range [100,120]. Then write all numbers in this range that haven't been chosen in ascending order. My solution works but there's a problem. The program breaks when I remove the braces from the constant LENGTH. I'm talking about the line with the arrow (<---) For some reason the rand starts generating negative numbers when I do. Why does this happen? Removing the const and working with a normal variable "length" also works.

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

#define MIN 100
#define MAX 120
#define LENGTH MAX - MIN + 1
//Range is [MIN, MAX]

void write_arr(int const arr[], int amount)
{
    int i;
    for (i = 0; i < amount; i++) {
        printf("%-3d ", arr[i]);
    }
    printf("\n");
}

int main()
{
    srand(time(NULL));
    int numbers[MAX - MIN];
    int i;
    for (i = 0; i < LENGTH; i++) {
        numbers[i] = i + MIN;
    }

    //write_arr(numbers, LENGTH);

    ///Now remove 20 random numbers -> We do this by setting the value of a number to something that can't occur normally (MIN-1)

    for (i = 0; i < LENGTH; i++) {
        int delete = rand() % (LENGTH); //<----------------- I can't remove these braces
        printf("%3d ", delete + MIN);
        numbers[delete] = MIN - 1;
    }
    printf("\n");

    //Now write all numbers that still have a valid value

    for (i = 0; i < LENGTH; i++) {
        if (numbers[i] != MIN - 1) {
            printf("%-3d ", numbers[i]);
        }
    }
    printf("\n");
    return 0;
}



Zwettekop
  • 93
  • 7
  • 3
    You should put the parentheses in the `#define`, e.g. `#define LENGTH (MAX-MIN+1)`. The reason it breaks is because the preprocessor just does text substitution, so without parentheses, you get `int delete = rand() % MAX - MIN + 1` which is evaluated as `(rand() % MAX) - MIN + 1`. – user3386109 Dec 22 '19 at 17:55
  • That actually fixed my problem thank you. A slide in our course uses this statement: "# define AANTAL MAX - MIN" Is this also incorrect then? – Zwettekop Dec 22 '19 at 17:59
  • 2
    Yes, the slide is incorrect, or at least bad practice. With the parentheses, the statement becomes `rand() % (MAX - MIN + 1)` which forces `MAX - MIN + 1` to be evaluated first. – user3386109 Dec 22 '19 at 18:01
  • 1
    Thank you now I understand. If you post this as an answer I'll accept it so you get reputation points. – Zwettekop Dec 22 '19 at 18:04

0 Answers0