You are not generating the 1000 random numbers required

5

I'm developing a program in C that randomly generates a thousand numbers and that in the end appears the largest and smallest of them. For this, I'm using rand() .

But I have a problem. When I run only less than 300 numbers are generated and not from 0 to 1000. But from 707 to 1000.

Look below what I did:

include stdio.h
include stdlib.h
include windows.h

main(){
   int numero,numero2;
   int total1 = 0;
   int total2 = 1001;

   for (numero = 1; numero != 1001; numero++){
       numero2 = rand () % 1000;
       printf("Numero %d: %d \n ",numero,numero2);

       if (numero2 > total1){
           total1 = numero2;
       }

       if (numero2 < total2){
           total2 = numero2;
       }
   }

   printf("\n");
   printf("O maior numero e: %d \n\n",total1);
   printf("O menor numero e: %d \n\n",total2);

   system("pause");
   return 0;
}

Where am I going wrong?

    
asked by anonymous 05.11.2014 / 22:06

1 answer

6

Your code has several syntax errors and is very disorganized, this makes it difficult to understand it. Even you who wrote it end up getting lost in it. Variable nomenclature would also help to better describe what the code does.

But the main problem was the misuse of the operator != (operator that tests the difference , that is, if the operands are different from each other, that has any (operator that tests if the first operand is less than the second). The first one does as long as it is different, ie it is to do nothing. I do not know how I was doing anything. The second operator, as the reading itself describes, does as long as "is less than". Then < starts at 1 and counts until it reaches 1001. As long as it is less than 1001, it repeats, so it will repeat a thousand times.

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

int main(){

    int numero, numero2;
    int total1 = 0;
    int total2 = 1001;

    for (numero = 1; numero < 1001; numero++){
        numero2 = rand () % 1000;
        printf("Numero %d: %d \n ", numero, numero2);

        if (numero2 > total1){
            total1 = numero2;
        }

        if (numero2 < total2){
            total2 = numero2;
        }
    }

    printf("\n");
    printf("O maior numero e: %d \n\n",total1);
    printf("O menor numero e: %d \n\n",total2);

    system("pause");
    return 0;
}

See running on ideone . And in Coding Ground . Also I put it in GitHub for future reference .

In it I did a little different, I put the srand () to start sowing a little better the pseudorandom numbers.

    
05.11.2014 / 22:19