本帖最后由 yuxijian2020 于 2021-4-9 23:40 编辑
你这写的....我稍微给你改了下
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#define ArraySize 1000001
#define maxkt 100
/*run this program using the console pauser or
add your own getch,system("pause") or input loop*/
double f1(double x, double a[], int n) //累计求和
{
int i;
long double p = 0;
for (i = 0; i <= n; i++)
p += a[i] * pow(x, i);
return p;
}
double f2(double x, double a[], int n) //乘法结合律
{
int i;
long double p = a[n];
for (i = n; i > 0; i--)
{
p = a[i - 1] + x * p;
}
return p;
}
double f1(double x, double a[], int n);
double f2(double x, double a[], int n);
clock_t start, end;
int main()
{
//double a[ArraySize];
double* a = (double*)malloc(ArraySize * sizeof(double));
if (a == NULL)
{
printf_s("空间申请失败...\n");
return -1;
}
memset(a, 0, ArraySize * sizeof(double));
int i;
double j;
for (i = 1; i < ArraySize; i++)
{
j = i;
a[i] = 1 / j;
}
a[0] = 1; //引入a[]
start = clock();
for (i = 0; i < maxkt; i++)
f1(1.2, a, ArraySize - 1);
end = clock();
double duration1 = (double)end - (double)start / CLK_TCK / maxkt;
printf("累计求和所用时间:%.2lf 毫秒\n", duration1);
long double t;
t = f1(1.2, a, ArraySize - 1);
printf("累计求和结果=%llf\n", t);
start = clock();
for (i = 0; i < maxkt; i++)
f2(1.2, a, ArraySize - 1);
end = clock();
double duration2 = (double)end - (double)start / CLK_TCK / maxkt;
printf("乘法结合律所用时间:%.2lf 毫秒\n", duration2);
long double y;
//f2(1.2, a, ArraySize - 1);
y = f2(1.2, a, ArraySize - 1);
printf("累计求和结果=%llf\n", y);
free(a);
return 0;
}
结果你就不要想了,我用了long double都还是溢出.... |