【问题标题】:Program won't return highest or smallest values using math methods程序不会使用数学方法返回最大值或最小值
【发布时间】:2021-03-06 23:09:00
【问题描述】:

帮助我试图让我的代码发出警报 最重要的数字输入和最低的为什么我的不这样做?

let price;
let items = 0; 
let sum=0;
let big = 0 ;
let small = 0;

price = Number(prompt("Please enter the price of the Item you choose to buy or enter -1 to stop: "));

while (price != -1){

    sum=sum+price;
    items++;
    avg = sum/items;
    Big = Math.max(Number(price));
    small = Math.min(Number(price));
    price = Number(prompt("Please enter the price of the Item you choose to buy or enter -1 to stop: "));
    
   
}

alert("You have purchased "+items+" items!");
alert("the sum of items you purchased is: $"+sum);
alert("the Averege of the items is: " + avg);
alert("The highest item price purchased was: "+ Big);
alert("The lowest item price was: "+ small);

【问题讨论】:

  • 你必须给Math.max()多个参数。它返回所有参数中最高的。
  • 如果你只给它一个参数,它只会返回那个,因为没有其他东西可以比较。
  • 你为什么写Number(price)?您在分配变量时将其转换为数字,您不必再次转换它。
  • 如何获得最高的输入回报
  • 比较当前输入和Big。如果更高,请替换Big

标签: javascript math methods while-loop


【解决方案1】:

使用函数 isNumeric 检查valid numbers。 使用名为itemsPurchased的数组存储所有有效购买not including empty string, negative numbers

使用template strings, destructuring assignment, Array.prototype.reduce() , Math.max(), spread operator , Math.min() and Array.prototype.length 得到想要的结果。

function isValidNumber(str) {
  if (typeof str != "string") return false;
  return (
    !isNaN(str) && 
    !isNaN(parseFloat(str))
  );
}

function purchaseCalculation() {
  let price,
    expensive,
    cheap,
    itemsNumber,
    average,
    total,
    itemsPurchased = [];

  price = prompt(
    "Please enter the price of the Item you choose to buy or enter -1 to stop: "
  );
  while (price !== "-1") {
    if (isValidNumber(price) && Number(price) >= 0) {
      itemsPurchased.push(Number(price));
    }
    price = prompt(
      "Please enter the price of the Item you choose to buy or enter -1 to stop: "
    );
  }

  expensive = itemsPurchased.length === 0 ? 0 : Math.max(...itemsPurchased);
  cheap = itemsPurchased.length === 0 ? 0 : Math.min(...itemsPurchased);
  total = itemsPurchased.reduce((total, item) => total + item, 0);
  itemsNumber = itemsPurchased.length;
  average = total === 0 ? 0 : total / itemsNumber;

  return [cheap, expensive, total, itemsNumber, average];
}


const [cheap, expensive, total, itemsNumber, average] = purchaseCalculation();
alert(
  `You have purchased ${itemsNumber} ${itemsNumber > 1 ? "items" : "item"}!`
);
alert(
  `The sum of ${
    itemsNumber > 1 ? "items" : "item"
  } you purchased was: $${total}`
);
alert(
  `The average of the ${itemsNumber > 1 ? "items" : "item"} was: ${average}`
);
alert(`The highest item price purchased was: ${expensive}`);
alert(`The lowest item price was: ${cheap}`);

【讨论】:

    猜你喜欢
    • 2021-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 2019-06-24
    • 2019-04-18
    • 2014-05-10
    • 1970-01-01
    相关资源
    最近更新 更多