示例代码 1:
/* 计算 1 - 1 / x + 1 / x * x - ... */
#include <stdio.h>
#include <sys/timeb.h>
int main(void)
{
double x;
int n;
printf("Please input x and n: ");
scanf_s("%lf%d", &x, &n);
struct timeb t1;
ftime(&t1); /* 求得当前时间 */
double totalSum = 1.0, subSum;
for (int i = 1; i <= n; ++i) {
subSum = 1.0;
for (int j = 1; j <= i; ++j) {
subSum = -subSum / x;
}
totalSum += subSum;
}
struct timeb t2;
ftime(&t2); /* 求得当前时间 */
long t = (long)(t2.time - t1.time) * 1000 + (t2.millitm - t1.millitm); /* 计算时间差 */
printf("totalSum = %lf, 用时 %ld 毫秒\n", totalSum, t);
return 0;
}
输出示例:
示例代码 2:
/* 计算 1 - 1 / x + 1 / x * x - ... */
#include <stdio.h>
#include <sys/timeb.h>
int main(void)
{
double x;
int n;
printf("Please input x and n: ");
scanf_s("%lf%d", &x, &n);
struct timeb t1;
ftime(&t1); /* 求得当前时间 */
double totalSum = 1.0, subSum = 1.0;
for (int i = 1; i <= n; ++i) {
subSum = -subSum / x;
totalSum += subSum;
}
struct timeb t2;
ftime(&t2); /* 求得当前时间 */
long t = (long)(t2.time - t1.time) * 1000 + (t2.millitm - t1.millitm); /* 计算时间差 */
printf("totalSum = %lf, 用时 %ld 毫秒\n", totalSum, t);
return 0;
}
输出示例: