gpt4 book ai didi

c - 我的代码中出现未知错误

转载 作者:太空宇宙 更新时间:2023-11-04 03:26:21 25 4
gpt4 key购买 nike

#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

想知道我需要对我的代码进行哪些更改,以及我是否可以改进我的代码。

最佳答案

函数 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);

关于c - 我的代码中出现未知错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40900098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com