samedi 25 juillet 2020

Problem with continue instruction after rand() function

I just wanted to solve an exercise that asks me to write a routine to generate a set of even random numbers between 2 to 10.

The problem is when printing, because I want that only the last number not to be followed by a comma. This is my code and these two execution

The problem is when printing, because I want the last number not to be followed by a comma.

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

int main()
{
    int i, a, b, c;

    i = a = b = c = 0;

    srand(time(NULL));

    for (i = 2; i <= 10; i++)
    {
        a = rand() % 8 + 2;

        if ((i <= 10) && (a % 2) != 0)
        {   
            continue;
        }
        printf((i < 10) ? "%d, " : "%d\n", a);
    }
    return 0;
}

and these two execution examples.

In one the comma does not appear at the end but in another it does. When debugging I see that the error happens when the last number is odd, because the continue statement causes it to go to the next iteration.

I appreciate any suggestion.




Aucun commentaire:

Enregistrer un commentaire