#include<stdio.h> #include<time.h> #include<math.h> long add1( long n ) { long i ,sum =0; for (i=1;i<=n;i++) sum+=i; return sum; } void AddTimel ( long n ) { clock_t t ; long sum; t=clock(); sum=add1(n); t=clock()-t; printf('方法1: '); printf('结果:1~%d之和:%ld ',n,sum); printf('用时:%lf秒 ',((float)t)/CLOCKS_PER_SEC); } long add2(long n) { return n*(n+1)/2; } void AddTime2(long n) { clock_t t; long sum; t=clock(); sum=add2(n); t=clock()-t; printf('方法2: '); printf('结果:1~%d之和:%ld ',n,sum); printf('用时:%lf秒 ',((float)t)/CLOCKS_PER_SEC); } int main() { int n ; printf('n(大于1000000):'); scanf('%d',&n); if (n<1000000) return 0; AddTimel(n); AddTime2(n); printf('作者:胡灿 '); return 1; }

C语言计算1到n的和:两种方法效率对比

原文地址: https://www.cveoy.top/t/topic/nlOd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录