简体   繁体   English

C++ 中模运算符的正确用法

[英]Correct usage of modulo operator's in C++

I am trying to teach myself c++.我正在尝试自学 c++。

On Sololearn I have a task , which is在 Sololearn 我有一个任务,那就是

You are making a program for a bus service.您正在为公共汽车服务制作程序。 A bus can transport 50 passengers at once.一辆公共汽车一次可以运送50名乘客。 Given the number of passengers waiting in the bus station as input, you need to calculate and output how many empty seats the last bus will have.给定在公交车站等候的乘客人数作为输入,您需要计算最后一班公交车有多少空座位。

Sample Input: 126样本输入:126

Sample Output: 24样品 Output:24

It also says I should use the "%" operator.它还说我应该使用“%”运算符。 This is the code I created:这是我创建的代码:

    int bus = 50;
    int stop;
    cin >> stop;
    cout<< stop % bus;
    return 0;

I get 12.我得到12。

What is the correct way?正确的方法是什么? I'm finding it difficult to understand what the modulo operator does.我发现很难理解模运算符的作用。 My understanding is that it divides as many times as it can and leaves the remainder (ie 16 % 3 = 1).我的理解是,它会尽可能多地划分并留下剩余部分(即 16 % 3 = 1)。

Modulos operator basically represents the leftover from the division模算子基本上代表除法的余数

so what we need to do is take the number of people that will remain in the last bus travel which is stop % bus and compute bus - (stop % bus)所以我们需要做的是计算将留在最后一班巴士旅行中的人数,即 stop % bus 和计算 bus - (stop % bus)

that way we know the number of empty seats on the last travel这样我们就知道上次旅行的空座位数

This is like each bus was filled to the fullest (50 people per bus) what will remain is 26 and so on the last bus the number of empty seats will be 50 - 26 = 24这就像每辆公共汽车都坐满了(每辆公共汽车 50 人)剩下的就是 26 个,所以最后一班公共汽车的空座位数将是 50 - 26 = 24

PS: 12 doesn't seem to be the right output of 126 % 50 it should be 26 PS:12 似乎不是正确的 output of 126 % 50 应该是 26

First you have to get the number of passengers首先你必须得到乘客的数量

int passengers;国际乘客; cin >> passengers; cin >> 乘客;

then you have to find how many passengers are left那么你必须找出还剩下多少乘客

int remainPass = passengers % 50; int 剩余通行证 = 乘客 % 50;

then you have to find how many seats are left那么你必须找到还剩多少个座位

int remainSeats = 50 - remainPass; int 剩余座位 = 50 - 剩余通行证;

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

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