la recogida de los números e imprimirlas
-
13-09-2019 - |
Pregunta
Lo que estoy tratando de lograr es la generación aleatoria de 100 0 y 1 a añadir a todos en una variable y luego imprimirlo. Lo que tengo en este momento no sé cómo hacer el trabajo. Si alguien puede explicar lo que estoy haciendo mal, yo estaría muy agradecido.
randstring (void){
int i;
int num;
char buffer[101];
i=100;
while(i>0, i--){
num = rand()%2;
strcpy(buffer, num);
}
return(buffer);
}
Lo que tenemos ahora es:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main (void){
printf("%f", randstring());
}
randstring (void){
int num;
char buffer[101];
int i = 100;
while(i-- >= 0) buffer[i] = rand() % 2;
return(buffer);
}
Solución
¿Qué hay de buffer[i] = (rand() % 2) ? '1' : '0';
en el cuerpo del bucle?
Y lo haría buffer [100] = 0;
Pero el peor problema es que no se puede volver memoria intermedia, porque tan pronto sus salidas de función, que se sobrescribe. Se asigna en la pila, y la pila se reutiliza cuando la función termina. Es necesario hacer a cualquiera de malloc y libre, o pasar de amortiguación y su longitud para esta función.
Lo que nos da:
#include <stdio.h>
#define RAND_LENGTH 100
char *randstring (char *buffer, int length);
int main (int a, char **b){
char buffer[RAND_LENGTH + 1];
printf("%s", randstring(buffer, RAND_LENGTH));
}
char *randstring (char *buffer, int length){
int i = length;
while(--i >= 0) {
buffer[i] = (rand() % 2) ? '1' : '0';
}
buffer[length] = 0;
return buffer;
}
Otros consejos
Prueba esto:
int i = 100;
while(i-- >= 0) buffer[i] = rand() % 2;