使用Modulo计算余数

时间:2013-11-05 20:38:00

标签: javascript modulo

    //How much pizza each party goer will recieve
    const slices = 3; //Number of slices 8
    var people = 8; //Number of people 25
    var pizzas = 10; //Number of pizzas 10

   //pizzas ordered times the number of slices, divided by the number of people & asign         slicePerson variable
   var slicePerson = (slices * pizzas)/people;
  //print out how many pieces per person
  console.log("Each person ate" + " " + slicePerson + " " + "slices of pizza at the party.")



  //Sparky gets what remainder of pizza
  //Slices by pizzas used modulo to give remainder with people
  var dogFood = 30 % people;
  //print out how many slices sparky got
 console.log("Sparky got" + " " + dogFood + " " + "slices of pizza.");

问题:

在披萨派对Sparky,主人的狗很兴奋,因为他在客人之间均匀分割切片后得到剩余的披萨。假设客人得到整片,Sparky会吃多少整片? 示例数据集:10个人,4个披萨和每个披萨8个切片意味着每个人吃3片,Sparky得到2片。 (请注意,这是一个示例,无论我为这些给定变量输入什么数字,您的代码都应该可以正常运行并给我准确的结果。)      鉴于: 不要为此创建新的给定变量/常量。而是使用你为Slice of Pie I设置的数量。      结果变量: Sparky可以吃的切片数量。     打印结果: “Sparky得到了X片披萨。”

我已经插入并尝试了尽可能多的方法,但我可以使用不同的数字。它总是关闭一点点。

1 个答案:

答案 0 :(得分:0)

var leftovers = (slicesPerPizza * numberOfPizzas) % numberOfGuests;
var slicesPerPerson = (slicesPerPizza * numberOfPizzas - leftovers) / numberOfGuests;

每位客人获得slicePerPerson,Sparky获得剩余的。