In VBScript, the sum of 1 to 100 is calculated.

Source: Internet
Author: User

This log is entirely inspired by reading a log. The original Article is evil eval and new function.

We seldom use the new array method to define arrays. I didn't expect the new array to be so useful. We can create n null elements through the new array (n, at the same time, there are n-1 gaps in the middle of n elements. Through join, we can place some things in the middle of these gaps to form a special string we need, which can not help but inspire me, this feature makes it easy for me to implement a continuous operation of regular elements without repeating ". For example, calculate the sum of values from 1. In the past, we needed to loop from 1 to 100 and then sum up, but we can use this feature of array through a simple lineCodeThe Code is as follows:Copy codeCode: var I = 0, sum = eval ('0' + new array (101). Join ('+ (++ I )'));

In addition, we can perform many similar mathematical operations, such as the following:Copy codeThe Code is as follows: eval ('0' + new array (11). Join ('+ math. Pow (+ + I, 2)') // calculates the sum of squares from 1 to 10.
Eval ('0' + new array (100/2). Join ('+ (I + = 2)') // calculate the sum of 2 + 4 + 6 +... 100

We used to perform these computation in a loop, and now we can use a line of code to handle it, so we have to sigh.Programming LanguageImplicit cleverness, there are always too many things in the programming world to be discovered.

The above JavaScript code is changed to vbs, which is the so-called hardcore solution of vbs exercises:

Copy code The Code is as follows: dim A (101)
Execute (join (a, "s = S + I: I = I + 1 :"))
Msgbox s

Original article: http://demon.tw/programming/no-loop-calculate-1-100-sum.html

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.