C++ 如何一步得到商和余数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8318272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:22:26  来源:igfitidea点击:

How can I get the quotient and the remainder in a single step?

c++cmodulointeger-division

提问by dtech

Possible Duplicate:
Divide and Get Remainder at the same time?

可能的重复:同时进行
除法和获取余数?

Is it possible to get both the quotient and the remainder of integer division in a single step, i.e., without performing integer division twice?

是否可以在一个步骤中同时获得整数除法的商和余数,即不执行两次整数除法?

回答by John Dibling

divwill do this. See referenceand example:

div会这样做。请参阅参考和示例:

/* div example */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  div_t divresult;
  divresult = div (38,5);
  printf ("38 div 5 => %d, remainder %d.\n", divresult.quot, divresult.rem);
  return 0;
}

Output:

输出:

38 div 5 => 7, remainder 3.

EDIT:

编辑:

The C Specification says:

C 规范说:

7.20 General utilities

7.20 一般公用事业

The types declared are size_t and wchar_t (both described in 7.17),
div_t
which is a structure type that is the type of the value returned by the div function,
ldiv_t
which is a structure type that is the type of the value returned by the ldiv function, and
lldiv_t
which is a structure type that is the type of the value returned by the lldiv function.

... but it doesn't say what the definition of div_tis.

...但它没有说明的定义div_t是什么。

回答by Greg Hewgill

Yes, there is a standard function called div()(and ldiv, and maybe even lldiv) that does this.

是的,有一个称为div()(和ldiv,甚至可能lldiv)的标准函数可以做到这一点。