C ++获得整数除法和余数的最佳方法 [英] C++ Best way to get integer division and remainder
问题描述
我只是想知道,如果我想要除以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。如果除数
b $ b
是一个字节值,则结果将被置于AL 和余数AH 。如果除数
是字值,则DX:AX除以src,结果存储在AX 中的
,而余数存储在DX 中。
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
srcNote: 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屋!