提示计算器的结果以NaN为单位

时间:2018-09-04 19:30:32

标签: javascript

我是初学者,正在研究初学者的问题,但需要一些帮助

我正在尝试编写自己的小费计算器应用程序,但结果是NaN。

我确信这是一个简单的解决方法,但是我还没有看到问题所在。我的代码如下。有人可以告诉我我在做错什么,导致我的finalCost导致NaN而不是billAmount + tipTotal吗?

var billAmount = prompt('What is your total bill?');

var tipAmount = prompt('How much do you want to tip');

console.log(billAmount);

var tip = tipAmount / 100;

var tipTotal = tip * billAmount;

function finalCost(billAmount, tipTotal) {
  return billAmount + tipTotal;
};

console.log("The tip is " + tipTotal);
console.log("The total bill is " + finalCost());

2 个答案:

答案 0 :(得分:1)

太近了!您只是错过了将值传递到最终的计算方法中。

var billAmount = prompt('What is your total bill?');

var tipAmount = prompt('How much do you want to tip');

console.log(billAmount);

var tip = tipAmount/100;

var tipTotal = tip*billAmount;

function finalCost(billAmount, tipTotal) {
	return billAmount + tipTotal;
};

console.log("The tip is " + tipTotal);
console.log("The total bill is " + finalCost(billAmount, tipTotal));

您还可以删除参数,仅在计算中使用“全局”值

var billAmount = prompt('What is your total bill?');

var tipAmount = prompt('How much do you want to tip');

console.log(billAmount);

var tip = tipAmount/100;

var tipTotal = tip*billAmount;

function finalCost() {
	return billAmount + tipTotal;
};

console.log("The tip is " + tipTotal);
console.log("The total bill is " + finalCost());

答案 1 :(得分:0)

还有一个问题。直接从float设置prompt()值并不能确保float值(默认情况下被视为string),因此将prompt()函数包装在{{ 1}}函数:

parseFloat()

这应该验证var billAmount = parseFloat(prompt('What is your total bill?')); var tipAmount = parseFloat(prompt('How much do you want to tip')); if(isNaN(billAmount) || isNaN(tipAmount)){ alert("Bill amount or Tip is Invalid"); } else { console.log("This bill is " + billAmount); var tip = tipAmount / 100; var tipTotal = tip * billAmount; console.log("The tip is " + tipTotal); console.log("The total bill is " + finalCost(billAmount, tipTotal)); } function finalCost(billAmount, tipTotal) { return billAmount + tipTotal; };billAmount的值是tipAmount,并且如果不是,则阻止进一步执行。