int foo(int n) { bool sign = true; //true表示正号,false表示负号 int sum = 0; for (int i = 1; i <= n; ++i) { if (sign) sum += i; else sum -= i; sign = !sign; } return sum; }
1. 老老实实的方法,费时费事 INT cal( int n ) { INT i ; INT total = 0 ; for( i = 1 ; i <= n ; i ++ ) { if( i % 2 == 0 ) total -= i ; else total += i ; } return total ; }
2. 我会采用的方法 INT cal( int n ) { if( n % 2 == 0 ) return ( 0 - n / 2 ) ; else return ( ( n + 1 ) / 2 ) ; }
第2个回答 2015-05-05
void func(int n) { if (n < 0) { return; } int c = 0; for (int i = 0; i < n; i++) { c += (i + 1); } cout<<c; }本回答被网友采纳