I want to make a program that returns the average of the numbers entered but i get this error: incompatible types when assigning to type ‘float *’ from type ‘float’
#include <stdio.h>
#include <stdlib.h>
#define CANT ((int)99)
float* promedio (float *dataPtr, int dataCant)
{
float *p;
int a;
float total;
for ( a = dataCant; a >= 0; a--) {
total = *dataPtr;
*dataPtr =1;
}
p = total / dataCant;
return (p);
}
int main (void)
{
float v[CANT],*q;
int i;
printf ("Ingrese numeros para calcular el promedio\r\n");
printf ("Use -1 para ver el promedio\r\n");
while ((i < CANT) || (v [i] != -1)) {
printf(" Ingrese un numero: \r \n");
scanf ("%f", &v[i]);
i ;
}
q = promedio (&v[0], i);
printf ("El promedio vale %f\r\n", *q);
free (v);
return (0);
}
CodePudding user response:
Your approach of returning a pointer from promedio doesn't make much sens.
You probably want this:
void promedio (float *dataPtr, int dataCant, float *result)
{
int a;
float total;
for ( a = dataCant; a >= 0; a--) {
total = *dataPtr;
dataPtr =1; // remove the *, you want to increment the pointer
} // not the thing it points to
*result = total / dataCant;
}
int main (void)
{
float v[CANT],*q;
int i;
printf ("Ingrese numeros para calcular el promedio\r\n");
printf ("Use -1 para ver el promedio\r\n");
while ((i < CANT) || (v [i] != -1)) {
printf(" Ingrese un numero: \r \n");
scanf ("%f", &v[i]);
i ;
}
float q;
promedio (&v[0], i); // you should write `v` innstead of the cumbersome `&v[0]`
printf ("El promedio vale %f\r\n", q); // q is a float, removge the *
// remove free (v), you can only free stuff allocated via malloc and friends
return (0);
}
Anyway, I have the strong impression you should read again the chapter dealing with pointers in your learning material.
It turns out you rather need this:
float promedio (float *dataPtr, int dataCant)
{
int a;
float total;
for ( a = dataCant; a >= 0; a--) {
total = *dataPtr;
dataPtr =1; // remove the *, you want to increment the pointer
} // not the thing it points to
return = total / dataCant;
}
CodePudding user response:
@Jabberwocky Thank you for your answer, thanks it I managed to solve the exercise. This is the answer (works)
#include <stdio.h>
#include <stdlib.h>
#define CANT ((int)99)
float promedio (float *dataPtr, int dataCant)
{
int a;
float total;
for ( a = dataCant; a >= 0; a--) {
total = *dataPtr;
dataPtr =1;
}
return (total / dataCant);
}
int main (void)
{
float v[CANT], q, a;
int i=0;
printf ("Ingrese numeros para calcular el promedio\r\n");
printf ("Use -1 para ver el promedio\r\n");
while ((i < CANT) && (a != -1)) {
printf(" Ingrese un numero: \r \n");
scanf ("%f", &a);
if (a != -1) {
v[i]=a;
i ;
}
}
q = promedio (&v[0], i);
printf ("El promedio vale %0.2f\r\n", q);
return (0);
}