验证性实验
求1~n的连续整数和
说明
对于给定的正整数n,求 1 + 2 + … + n 1+2+…+n 1+2+…+n,采用逐个累加和 n ( n + 1 ) 2 \frac {n(n+1)} 2 2n(n+1)(高斯法)两种解法。
对于相同的n,给出这两种解法的求和结果和求解时间,并用相关数据进行测试。
- clock_t类型、clock()函数和CLOCKS_PER_SEC常量均在time.h头文件中声明。
- clock_t是时钟数据类型(长整型数)
- clock()函数返回CPU时钟计时单元数(以毫秒为单位)
- CLOCKSPER_SEC是一个常量,表示1秒包含的毫秒数。
- 表达式((float) t)/CLOCKS_PER_SEC返回t转换成的秒数;
放码
//文件名:exp1-1.cpp
//求1+2+...+n
#include <stdio.h>
#include <time.h> // clock_t, clock, CLOCKS_PER_SEC
#include <math.h>
//方法1:老实累加
long add1(long n)
{
long i, sum = 0;
for (i = 1; i <= n; i++)
sum += i;
return(sum);
}
void AddTime1(long n) /* 采用方法1的耗时统计 */
{
clock_t t = clock();
long sum = add1(n);
t = clock() - t;
printf("方法1:\n");
printf(" 结果:1~%d之和:%ld\n", n, sum);
printf(" 用时:%lf秒\n", ((float)t) / CLOCKS_PER_SEC);
}
//方法2:用公式
long add2(long n) /* 方法2:求1+2+...+n */
{
return(n * (n + 1) / 2);
}
void AddTime2(long n) /* 采用方法2的耗时统计 */
{
clock_t t = clock();
long sum = add2(n);
t = clock() - t;
printf("方法2:\n");
printf(" 结果:1~%d之和:%ld\n", n, sum);
printf(" 用时:%lf秒\n", ((float)t) / CLOCKS_PER_SEC)