我只是想知道,如果我想要除以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 $ bint 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 ++获得整数除法和余数的最佳方法
发布评论