在我需要总量的时候生产NAN

Producing NAN when i need the total

本文关键字:候生产 NAN      更新时间:2023-09-26

程序需要为presentValuemonthsinterest的速率生成一个介于.1%-.10%之间的随机数。

在进行最后的计算时,我得到了NaN。

var count = 5;
function futureValue(presentValue, interest, months) {
  var step1 = 1 + Number(interest);
  var step2 = parseFloat(Math.pow(step1, months));
  var step3 = presentValue * step2;
  return "The future value is: " + step3;
}
for (i = 0; i < count; i++) {
  var presentValue = Math.floor(Math.random() * 100)
  var interest = ((Math.random() * .10 - 0.1) + .1).toFixed(2)
  var months = Math.floor(Math.random() * 100)
  futureValue(presentValue, interest, months)
  console.log("The present value is: " + presentValue);
  console.log("The interest rate is: " + interest);
  console.log("The number of months is: " + months);
  console.log(futureValue());
}

您需要传入参数:

console.log(futureValue())

console.log(futureValue(presentValue,interest,months))  

这一行正确地计算了未来的值,但对它没有任何作用。

futureValue(presentValue,interest,months);

此行返回调用不带参数的futureValue函数,该函数返回NaN并将结果写入日志。

console.log(futureValue());

您应该做的是将值分配给一个变量,然后记录该值:

var futureVal = futureValue(presentValue,interest,months);
console.log(futureVal);

或者只是:

console.log(futureValue(presentValue,interest,months));

您正在调用不带参数的futureValue()。它返回NaN(不是数字),因为您使用"未定义"进行计算,实际上,它不是数字,

尝试:

var count = 5
function futureValue(presentValue,interest,months){
var step1 = 1 + Number(interest);
var step2 = parseFloat(Math.pow(step1,months));
var step3 = presentValue*step2;
return("The future value is: " + step3);
}
for (i=0;i<count;i++){
var presentValue = Math.floor(Math.random()*100)
var interest = ((Math.random()*.10-0.1)+.1).toFixed(2)
var months = Math.floor(Math.random()*100)
var fv = futureValue(presentValue,interest,months) //save your futureValue in a variable.
console.log("The present value is: " + presentValue);
console.log("The interest rate is: " + interest);
console.log("The number of months is: " + months);
console.log(fv)//log your calculated future value
}

这是因为

return("The future value is: " + step3);

是一个字符串。因此,它确实不是一个数字。

您应该返回JUST数字,然后创建字符串。

一旦调用futureValue(presentValue,interest,months),该值就会消失。如果你想console.log结果,你应该把它存储在一个变量中,然后console.log。