IT company 100 question-12-calculate 1 + 2 +... + N

Source: Internet
Author: User

Problem description:

1 + 2 +... + N. the keyword such as multiplication and division, for, while, if, else, switch, and Case and the condition judgment statement (? B: C ). Analysis: Use static variables of the class to implement:If new contains N arrays of this type, the constructor of this class will be called N times. Code implementation:
 1 // 12.cc 2 #include <iostream> 3 using namespace std; 4  5 class Object { 6 public: 7     Object() { 8         ++N; 9         Sum += N;10     }11     static void reset() { N = 0; Sum = 0; }12     static int get_sum() { return Sum; }13 14 private:15     static int N;16     static int Sum;17 };18 19 int Object::N = 0;20 int Object::Sum = 0;21 22 int sum(int n) {23     Object::reset();24 25     Object* a = new Object[n];26 27     delete []a;28     a = 0;29 30     return Object::get_sum();31 }32 33 int main() {34     int n = 10;35     cout << "The sum is: " << sum(n) << endl;36     return 0;37 }

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.