C语言 如何解决“类型不兼容”的问题?

v6ylcynt  于 2022-12-11  发布在  其他
关注(0)|答案(2)|浏览(210)

我想做一个程序,返回输入的数字的平均值,但我得到这个错误:从型别'float'指派给型别'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);
}
lsmepo6l

lsmepo6l1#

从promedio返回指针的方法没有多大意义。
您可能需要:

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);
}

无论如何,我有强烈的印象,你应该再读一遍你的学习材料中处理指针的章节。
事实证明你更需要这个:

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;
}
ego6inou

ego6inou2#

@Jabberwocky谢谢你的答案,谢谢它我设法解决了练习。这是答案(作品)

#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);
}

相关问题