简体   繁体   中英

I need to get a sum of values

I am having a brain cramp here

I have a function that calculates the values of a $10,000 annual investment. I use an array that holds the annual rate of returns. In order words, over a ten year period a person will have invested $100,000. The first $10,000 will be invested for 10 years, the next $10,000 for nine years, etc. and the last $10,000 will only be invested for one year. The investments are made at the beginning of each year and the rates of return are calculated at the end of each year.

Here is my code

// this is the array containing the rates of return

var values = [32.60,7.44,-10.46,43.72,12.06,0.34,26.64,-8.81,22.61,16.42]

var rate; var FV; var PV;

function doit() {
   var result=document.getElementById("result");
    for (j=0;j<values.length;j++){
    PV=10000;
      for (i=j;i<values.length;i++){
      rate = values[i]/100;
      FV = (PV * (1+rate));
      PV = FV;
      }
    PV=Number(PV).toFixed(2);
    result.innerHTML+="$" + PV + "<br>";
    }
 }

And here is the html output:

$33981.31 - (the value of $10,000 after 10 years)

$25626.93 - (the value of next $10,000 after 9 years)

$23852.32 - (the value of next $10,000 after 8 years)

$26638.73 - (etc)

$18535.16

$16540.39

$16484.34

$13016.69

$14274.26

$11642.00 - (the value of last $10000 after 1 year)

These are the values of the variable PV as generated by my loop

My problem is how do I get the sum of these values in order to show the total value of the investment, ie the result of investing $10,000 a year for ten years. The actual result is $200,592.13

TIA

You could declare a total variable above the function:

var total = 0 ;
function doit()
{ 
    ...
    total += PV; // (this is at the end of the function)   
}
function gettotal()
{
    result.innerHTML += "Total: $" + total;
}

Do you want to see total sum of money? It looks simple.

var sum = 0;

and inside cycle: sum = sum + PV

I feel that you need something else

Use the += operator to append to a variable outside your loop. For the most accuracy and speed you should append your number before using toFixed as it both floors and converts it to a string.

function doit() {
   var sum = 0;
   for (j=0;j<values.length;j++){
      ...
      sum += PV; // Add to sum, best to do before flooring it
      PV=Number(PV).toFixed(2);
   }
   return sum;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM