Thanks for the example, it was very useful, the program now works like a charm .
I hope it's not a problem if I use this thread to ask another question about a different code:
Code:
#include <stdio.h>
#include <stdlib.h>
#define M 300
int partedec(float f); /*dichiarazione funzioni*/
void ordinadec(float v[],int dim);
main()
{
FILE *input;
char nomefile[M];
float array[M],gruppo1[M],gruppo2[M],gruppo3[M];
printf("Inserici il nome del file:\n");
scanf("%s", &nomefile);
input=fopen(nomefile,"r");
int i=0,numfloat=0;
while((fscanf(input,"%f",&array[i]))!=EOF) i++; /*creazione array*/
numfloat=i;
printf ("Il vettore letto presenta %d elementi:\n",numfloat);
for (i=0;i<numfloat;i++) printf("%.2f\n", array[i]);
ordinadec(array,numfloat);
printf("Il vettore ordinato e':\n");
for(i=0;i<numfloat;i++)
printf("%.2f\n",array[i]);
int j,p,k;
j=0;k=0;p=0;
for(i=0;i<numfloat;i++)
{ /*divides the array in three groups based on the decimal component of the float numbers*/
if (partedec(array[i])>=0 && partedec(array[i])<=39) /*.00<=decimal part<=.39*/
{
gruppo1[j]=array[i];
j++;
}
if (partedec(array[i])>39 && partedec(array[i])<=69) /*.39<decimal part<=.69*/
{
gruppo2[p]=array[i];
p++;
}
if (partedec(array[i])>69 && partedec(array[i])<=99) /*.69<decimal part<=.99*/
{
gruppo3[k]=array[i];
k++;
}
}
printf ("Stampa per gruppi:\n");
printf("-------------------");
printf("Gruppo 1 (parte decimale compresa tra .00 e .39)\n"); /*prints out the different groups*/
for (i=0;i<j;i++) printf("%f\n",gruppo1[j]);
printf("Gruppo 2 (parte decimale compresa tra .40 e .69)\n");
for (i=0;i<p;i++) printf("%f\n",gruppo2[p]);
printf("Gruppo 3 (parte decimale compresa tra .70 e .99)\n");
for (i=0;i<k;i++) printf("%f\n",gruppo3[k]);
system("PAUSE");
}
int partedec(float f) /*returns the decimal component of a float number*/
{ int dec;
f=f*100;
dec=f;
do dec=dec-100;
while (dec>=100);
return(dec);
}
void ordinadec(float v[],int dim) /*sort element by their decimal part*/
{
int i, ordinato;
float temp;
ordinato=0;
while(ordinato==0)
{
ordinato=1;
for(i=1;i<dim;i++)
{
if(partedec(v[i])<partedec(v[i-1]))
{
temp=v[i];
v[i]=v[i-1];
v[i-1]=temp;
ordinato=0;
}
}
}
}
The code compiles and works fine, but the assignment "gruppo1[j]=array[i]" creates some problem:the numbers are plain wrong, gruppo1 and gruppo2 contains only 0.00 numbers, and gruppo3 contains some crazy random number. The number of elements in each 'gruppo' array is right. What did I mess up this time?
Thanks for helping out a newbie (again )