-1
This code is leading me to an infinite cycle and I can’t figure out why.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void
troca (double *n1, double *n2)
{
double n;
n = *n1;
*n1 = *n2;
*n2 = n ;
}
void
ordena (double *r, int size)
{
int t;
int i;
while (1)
{
t = 0;
{
for (i=0;i<size-1;i++)
{
if(r[i] > r[i+1])
{
troca (&r[i], &r[i+1]);
t = 1 ;
}
}
if(t == 0)
break;
}
}
}
int
main(int argc, char **argv)
{
FILE *f1 ;
int i ;
int j=0 ;
int N ;
int k ;
double Min ;
double Max ;
double *reais;
double n ;
char c ;
sscanf(argv[1],"%d",&N) ;
sscanf(argv[2],"%lf",&Min);
sscanf(argv[3],"%lf",&Max);
f1 = fopen("f1.txt", "wb") ;
srand(time(NULL));
while (1)
{
if (j == 0)
{
reais = (double*)malloc((N)*sizeof(double));
j=1;
}
else
reais = realloc(reais, (N)*sizeof(double));
n = Max - Min;
for (i=0;i<N;i++)
{
reais[i] = Max - ((double) rand()/(double) RAND_MAX )*n;
//printf("%9lf",reais[i]);
}
ordena(reais, N);
k = 0;
for (i=0;i<N;i++)
{
printf("%9lf",reais[i]);
k++;
if (k == 5)
{
k = 0;
printf("\n");
}
}
printf("\nDeseja repetir as operacoes:\n1-Repetir\n2-Sair\nR:");
c = getchar();
if (c == '1')
{
printf("\nIntroduza novos valores de N, Min e Max:");
scanf("%d %lf %lf", &N, &Min, &Max);
continue;
}
if (c == '2')
{
free(reais);
break;
}
}
return 0;
}
The program takes three arguments from the command line, N, the number of reals the user wants to generate, Max and Min the limits of the generated values. With these values is generated a vector of doubles with the necessary size that is then ordered. So far everything works well. The problem is that when I ask for new arguments, I enter an infinite loop
Dude, first tell me what you intend to do.. with these variable names, you can’t understand anything. Plus, there are 2
while(1)
in the code, one of which is enough to throw you into an infinite loop.– Guilherme IA
The program takes three arguments from the command line, N, the number of reals the user wants to generate, Max and Min the limits of the generated values. With these values is generated a vector of doubles with the necessary size that is then ordered. So far everything works well. The problem is that when I ask for new arguments, I enter an infinite loop.
– Vasco Pinhão