简体   繁体   English

使用模数计算余数

[英]Using Modulo to calculate remainder

    //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.");

the question: 问题:

At the pizza party Sparky, the host's dog is excited, because he gets the leftover pizza after the slices have been divided up evenly among the guests. 在披萨派对Sparky上,主人的狗很兴奋,因为主人将切片均匀地分成客人后得到了剩下的披萨。 Assume guests get whole slices, how many whole slices will Sparky feast on? 假设客人得到了整块,Sparky盛宴要铺几块? Example data set: 10 people, 4 pizzas and 8 slices per pizza will mean each person eats 3 slices and Sparky gets 2 slices. 示例数据集:10个人,4个比萨饼和每个比萨饼8片将意味着每个人吃3片,Sparky得到2片。 (Note that this is an example, your code should work and give me the accurate results no matter what numbers I put in for those given variables.) Given: Don't make new given variables/constants for this. (请注意,这是一个示例,无论我为这些给定变量输入多少数字,您的代码都应该起作用并给我准确的结果。)给定:请勿为此创建新的给定变量/常量。 Instead use the givens you set up for Slice of Pie I. Result Variables: Number of slices Sparky gets to eat. 取而代之的是使用您为Pie I切片设置的给定值。结果变量:Sparky可以食用的切片数。 Result to Print: “Sparky got X slices of pizza.” 打印结果:“ Sparky得到了X片披萨。”

I've plugged and tried as many methods as I could think of but I can get it to work with different numbers. 我已经插入并尝试了尽可能多的方法,但是我可以将其用于不同的数字。 It's always off by a tiny bit. 它总是一点点偏离。

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

each guest gets slicesPerPerson, and Sparky gets the leftovers. 每个来宾获得slicesPerPerson,Sparky获得剩菜剩饭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM