On that day, the instructor gave a question and asked us to do it without recursion or loop ~ Sum of 100?
I wrote a code and sent it out today to see if you have any other good methods! I hope I can leave a message in a good way ,,,
The Code is as follows:
// Do not use loops or recursive summation! (C ++/VC +++ 6.0)
# Include <iostream>
Using namespace std;
Class calculate
{
Public:
Calculate ();
Int getsum ();
Static int N;
Static int SUM;
};
Int calculate: N = 0;
Int calculate: SUM = 0;
Calculate: calculate ()
{
N ++; www.2cto.com
SUM + = N;
}
Int calculate: getsum ()
{
ReturnSUM;
}
Void main ()
{
Intmax, min;
Cout <"Enter the sum range:" <endl;
Cout <"input minimum (min> 0):" <endl;
Cin> min;
While (min <0) {// The input in min is invalid. A message is displayed, prompting you to enter the parameter again;
Cout <"the minimum number of inputs (min> 0) is invalid. Enter again:" <endl;
Cin> min;
}
Cout <"input maximum (max> 0 and max> = min):" <endl;
Cin> max;
While (max <0 | max <min) {// the input of max is invalid. A prompt is displayed, prompting you to re-enter it;
Cout <"the maximum number of inputs (max> 0 & max> = min) is invalid. re-enter:" <endl;
Cin> max;
}
Calculate: N = (min-1 );
Calculate * p = new calculate [max-min + 1];
Cout <min <"~ "<Max <" sum: "<p-> getsum () <endl;
Delete [] p;
}
This method is implemented using the call of default constructor of The Destructor and the features of static data members, in fact, the automatic repeated calls of the Destructor here can also use the C ++ container instead of new, as long as the container contains objects, such as vector, because when the container contains class objects, When you define the number of elements, it will automatically call the destructor to initialize the object!
I don't know if you have any other good methods. I 'd like to leave a message to share with you (only available in C/C ++ !)
From wudemiao's column