Using operators in a document

In the following example, you use the Math.round() method to round calculations to an arbitrary number of decimal places. This method rounds the value of the score parameter up or down to the nearest integer, and then returns the value. After you slightly modify the ActionScript, you can make Flash round numbers to a certain number of decimal places instead.

In the example, you also use the division and multiplication operators to calculate a user's score based on the number of correct answers divided by the total number of questions that are asked. The user's score can multiply by a number and display to get a score between 0% and 100%. Then you use the addition operator to concatenate the user's score into a string that is displayed in the Output panel.

To use operators in ActionScript:

  1. Create a new Flash document.
  2. Type the following ActionScript on Frame 1 of the main Timeline:
    var correctAnswers:Number = 11;
    var totalQuestions:Number = 13;
    //round to the nearest integer
    //var score:Number = Math.round(correctAnswers / totalQuestions * 100);
    //round to two decimal places
    var score:Number = Math.round(correctAnswers / totalQuestions * 100 * 100) / 100;
    trace("You got " + correctAnswers + " out of " + totalQuestions + " answers correct, for a score of " + score + "%.");
    
  3. Select Control > Test Movie.

    The Output panel displays the following text:

    You got 11 out of 13 answers correct, for a score of 84.62%.
    

    When you call Math.round() in this example, the score rounds to the nearest integer (85) and is displayed in the Output panel. If you multiply the number by an additional 100, before you call Math.round(), and then divide by 100, you can make Flash round the number to 2 decimal places. This results in a more accurate score.

  4. Try changing the correctAnswers variable to 3 and select Control > Test Movie to test the SWF file again.

If you are building a testing application, you might want to create a series of true/false or multiple choice questions using the RadioButton and Label components. After users finish answering each of the questions and click the submit button, you can compare their answers to an answer key and then calculate their score.


Flash CS3


 

Send me an e-mail when comments are added to this page | Comment Report

Current page: http://livedocs.adobe.com/flash/9.0/main/00000745.html