C ++获得整数除法和余数的最佳方法 [英] C++ Best way to get integer division and remainder

查看:711
本文介绍了C ++获得整数除法和余数的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道,如果我想要除以b,并且对结果c和余数感兴趣(例如,我有秒数,并想分裂成分和秒),什么是最好的方法吗?



  int c =(int)a / b; 
int d = a%b;

  int c =(int)a / b; 
int d = a - b * c;

  double tmp = a / b; 
int c =(int)tmp;
int d =(int)(0.5+(tmp-c)* b);



也许有魔法

$ p

解决方案

在x86上,剩余部分是除法本身的副产品,体面的编译器应该能够使用它(而不是再次执行 div )。


指令: DIV src

注意:无符号除法。将累加器(AX)除以src。如果除数
是一个字节值,则结果将被置于AL 和余数AH 。如果除数
是字值,则DX:AX除以src,结果存储在AX 中的
,而余数存储在DX
中。

b $ b



  int c =(int)a / b; 
int d = a%b; / *可能使用除法的结果。 / / b $ b


I am just wondering, if I want to divide a by b, and am interested both in the result c and the remainder (e.g. say I have number of seconds and want to split that into minutes and seconds), what is the best way to go about it?

Would it be

int c = (int)a / b;
int d = a % b;

or

int c = (int)a / b;
int d = a - b * c;

or

double tmp = a / b;
int c = (int)tmp;
int d = (int)(0.5+(tmp-c)*b);

or

maybe there is a magical function that gives one both at once?

解决方案

On x86 the remainder is a by-product of the division itself so any half-decent compiler should be able to just use it (and not perform a div again). This is probably done on other architectures too.

Instruction: DIV src

Note: Unsigned division. Divides accumulator (AX) by "src". If divisor is a byte value, result is put to AL and remainder to AH. If divisor is a word value, then DX:AX is divided by "src" and result is stored in AX and remainder is stored in DX.

int c = (int)a / b;
int d = a % b; /* Likely uses the result of the division. */

这篇关于C ++获得整数除法和余数的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆