将JavaScript代码分解为函数

时间:2017-10-07 03:45:56

标签: javascript helpers

新手学生编码员,

在这里和我正在开发一个程序,可以提醒程序,一旦你输入你给它的金额,它将计算小费,并征税,以获得用户拥有的总金额。我把基本代码缩小并分成了函数,但是当我输入一个数字时,它显示为未识别。

这是我的代码:

const TAXRATE=.095
const TIPRATE=.2

function foodCharge (foodCharge) {
  return parseFloat(prompt("please enter the amount"));
}
foodCharge ();

function taxAmount (foodCharge,TAXRATE) {
  return parseFloat(foodCharge*TAXRATE);
}

taxAmount();


function subAmount (foodCharge,taxAmount) {
  return parseFloat(foodCharge+taxAmount);
}
subAmount ();

function tipAmount (TAXRATE,subAmount) {
  return parseFloat (TAXRATE*subAmount);
}
tipAmount ();


function grandTotal (foodCharge, taxAmount, tipAmount) {
  return grandTotal=parseFloat(foodCharge+taxAmount+tipAmount)
}
grandTotal ();

function finalCost(foodCharge,taxAmount, tipAmount, grandTotal ) { 
   alert ("Meal cost: "+ foodCharge + " \nTax: " + taxAmount + "  \nTip: " + 
    tipAmount +" \nGrand total: " + grandTotal);
}
finalCost();

2 个答案:

答案 0 :(得分:0)

您可以在finalCost内调整要调用的功能。请注意,只有parseFloat()函数

才需要foodCharge

const TAXRATE = .095
const TIPRATE = .2

function foodCharge() {
  return parseFloat(prompt("please enter the amount"));
}

function taxAmount(charge, tax) {
  return charge * tax;
}

function subAmount(charge, tax) {
  return charge + tax;
}

function tipAmount(tip, sub) {
  return tip * sub;
}

function grandTotal(charge, tax, tip) {
  return charge + tax + tip;
}

function finalCost() {

  let _foodCharge = foodCharge();
  let _taxAmount = taxAmount(_foodCharge, TAXRATE);
  let _subAmount = subAmount(_foodCharge, _taxAmount);
  let _tipAmount = tipAmount(TIPRATE, _subAmount);
  let _grandTotal = grandTotal(_foodCharge, _taxAmount, _tipAmount);

  alert("Meal cost: " + _foodCharge + " \nTax: " + _taxAmount + "  \nTip: " +
    _tipAmount + " \nGrand total: " + _grandTotal);
}

finalCost();

答案 1 :(得分:0)

只有从字符串解析浮点数时才需要 parseFloat 函数。您不需要解析常规数学运算的结果(如果两个数字都不是字符串)。将函数作为参数传递给 alert()时,必须使用括号 () 进行传递,否则将引用传递给函数。

如果我正确理解你的问题,这是你的程序:

const TAXRATE=0.095
const TIPRATE=0.2


function foodCharge (foodCharge) {
  return parseFloat(prompt("please enter the amount"));
}
var charge = foodCharge ();


function taxAmount (charge, rate) {
  return charge*rate;
}
var tax = taxAmount(charge, TAXRATE);


function subAmount (charge,tax) {
  return charge+tax;
}
var amount = subAmount (charge,tax);


function tipAmount (rate,amount) {
  return rate*amount;
}
var tip = tipAmount(TAXRATE,amount);


function grandTotal () {
  return charge+tax+tip;
}


function finalCost() {
  alert ("Meal cost: "+ charge + " \nTax: " + tax + "  \nTip: " + amount +" \nGrand total: " + grandTotal());
}
finalCost();