Problem description: 1 + 2 +... + N. You cannot use keywords such as multiplication and division, for, while, if, else, switch, and case, as well as condition judgment statements.
It is of little practical significance, and the knowledge involved in the questions is still good!
Method 1: Use the constructor to solve the problem.
# Include <iostream> using namespace std; class Plus {public: Plus () {++ I, sum + = I ;} // remove the following reset function and try static void reset () {I = 0; sum = 0;} // remove the following static keyword and try static int getSum () {return sum;} private: static int I; static int sum;}; int Plus: I = 0; int Plus: sum = 0; int cacSum (int n) {// only the static function can call Plus: reset (); Plus * test = new Plus [n]; delete [] test; return Plus: getSum ();} int main () {int I = 100; int result = cacSum (I); cout <"result =" <result <endl; system ("pause "); return 0 ;}
Method 2 is solved by recursive method, sum (n) = sum (n-1) + n
Int getSum (int n) {int result = 0; (n> 0) & (result = getSum (n-1) + n); return result ;}