how to do a random array counter in C

0

good, the program consists of making a series of rolls N of a dice and counting the number of times a number ordered by screen. This is the code I have made but something is wrong with the counter :( Thanks in advance.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 500
#define M 6

void obtenerRonda( int A[] ) {    
  int array[N];
  int i;
  srand( time( NULL ) );

  for( i = 0; i < N; i++ ) {
    array[i] = 1 + ( rand( ) % M );
    printf( "-%d-", array[i] );
  } 
}

int repeticion( int V[] ) {
  int i ;
  int t = 0;
  int numero;

  printf( "\nQue numero quieres saber cuantas veces se ha repetido" );
  scanf( "%d", &numero );

  for( i = 0; i < N; i++ ) {
    if( V[i] == numero ) {
      t++;
    }
  }

  printf( "el numero %d se repite %d veces ", numero, t );
}

int main( void ){
  int A[N];

  obtenerRonda( A );
  repeticion( A );
}
    
asked by cornetto 06.11.2017 в 19:57
source

1 answer

2

The error you have in the program is that the int A[N] fix has not been initialized correctly. You are only initializing the local array int array[N] in the function void obtenerRonda( int A[] ) when you should apparently use A[] .

This is the right implementation:

void obtenerRonda( int A[] ) {    
  int i;
  srand( time( NULL ) );

  for( i = 0; i < N; i++ ) {
      A[i] = 1 + ( rand( ) % M );
      printf( "-%d-", A[i] );
   } 
}

You will notice that I deleted the variable int array[N] . As a comment, the array array [] will be created in the function stack and will be "destroyed" once exiting the function. Actually in int A[] not having been initialized you had junk values.

The complete code can be found here

    
answered by 06.11.2017 / 21:22
source