寫一個函數(shù)計算當參數(shù)為n(n很大)時的值 1-2+3-4+5-6+7......+n
方法一:依次循環(huán)
#include<stdio.h>
#include<stdlib.h>
long fn(long n);
int main(void)
{ long n=0;
printf("input n\n");
scanf("%ld",&n);
printf("result=:%ld",fn(n));
system("pause");
return 0;
}
long fn(long n)
{
long temp=0;
int i,flag=1;//用FLAG控制正負號的交替 ,I 從1循環(huán)到N
if(n<=0)
printf("error: n must > 0");
for(i=1;i<=n;i++){
temp=temp+flag*i;
flag=(-1)*flag;}
return temp;
}
方法二:比起上一個程序,第二個涉及到乘法指令的語句改為執(zhí)行加法指令,既達到要題目的要求而且運算時間上縮短了很多!而代價僅僅是增加了一個整型變量!
實現(xiàn)全碼:
long fn(long n)
{
long temp=0;
int j=1,i=1,flag=1;
if(n<=0)
{
printf("error: n must > 0);
exit(1);
}
while(j<=n)
{
temp=temp+i;
i=-i;
i>0?i++:i--;
j++;
}
return temp;
}
方法三:直接跳過循環(huán)!!!整體上看,考慮到1-2+3-4+.....n的規(guī)律.. 其值等于中間數(shù)..
實現(xiàn)代碼如下:
long fn(long n)
{
if(n<=0)
{
printf("error: n must > 0");
exit(1);
}
if(0==n%2)
return (n/2)*(-1);
else
return (n/2)*(-1)+n;
}
是很強悍吧?我說過了嘛,是越來越優(yōu)噻~
posted on 2007-11-11 22:15
很笨的蛋 閱讀(280)
評論(0) 編輯 收藏 引用 所屬分類:
編程 C C++