#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define Pi 3.14159265358979323846
#define MAX_DATA 20
double Find_GrowthRate(double Data_6hr[MAX_DATA],double Data_24hr[MAX_DATA]);
double Find_DoublingTime(double GrowthRate[MAX_DATA]);
int main()
{
int i;
double t1;
double Data_6hr[MAX_DATA] = {2.3,3.3,4.3,5.3,6.3,7.3,8.3,9.3,10.3,11.3,12.3,13.3,14.3,15.3,16.3,17.3,18.3,19.3,20.3,21.3};
double Data_24hr[MAX_DATA] = {4.2,5.2,6.2,7.2,8.2,9.2,10.2,11.2,12.2,13.2,14.2,15.2,16.2,17.2,18.2,19.2,20.2,21.2,22.2,23.2};
Find_GrowthRate(Data_6hr,Data_24hr);
double *GrowthRate;
printf("Growth Rates\n");
for(i=0;i<MAX_DATA;i++){
printf("%lf \n",*(GrowthRate+i));
}
Find_DoublingTime(GrowthRate);
printf("Average Doubling Time");
printf("%lf", t1);
return 0;
}
double Find_GrowthRate(double Data_6hr[MAX_DATA], double Data_24hr[MAX_DATA])
{
int i;
double *GrowthRate;
GrowthRate = (double*)malloc(MAX_DATA*sizeof(double));
for(i=0;i<MAX_DATA;i++){
double PopulationSize_t1 = (Pi * pow((Data_6hr[i]/ 2),2));
printf("%lf\n",PopulationSize_t1);
double PopulationSize_t2 = (Pi * pow((Data_24hr[i]/ 2),2));
printf("%lf\n",PopulationSize_t2);
double x = ((PopulationSize_t2 - PopulationSize_t1) / PopulationSize_t1);
*(GrowthRate+i) = x;
}
printf("Growth Rates\n");
for(i=0;i<MAX_DATA;i++){
printf("%lf \n",*(GrowthRate+i));
}
return GrowthRate;
}
我收到的错误是: -
错误:返回类型'double *'但是'double is expected
时出现不兼容的类型想知道我需要做的代码中的更改是什么,以及我是否可以让我的代码更好。
答案 0 :(得分:1)
函数Find_GrowthRate
被声明为具有返回类型double
double Find_GrowthRate(double Data_6hr[MAX_DATA],double Data_24hr[MAX_DATA]);
^^^^^^
但是在函数定义中,函数返回类型为double *
double Find_GrowthRate(double Data_6hr[MAX_DATA], double Data_24hr[MAX_DATA])
{
int i;
double *GrowthRate;
//...
return GrowthRate;
^^^^^^^^^^
}
此外还有内存泄漏,因为指针GrowthRate
指向的动态分配的内存未被释放。
在这个循环中
double *GrowthRate;
printf("Growth Rates\n");
for(i=0;i<MAX_DATA;i++){
printf("%lf \n",*(GrowthRate+i));
}
使用未初始化的变量GrowthRate
会导致未定义的行为。
未初始化的变量t1
double t1;
//...
printf("%lf", t1);