C ++获得整数除法和余数的最佳方法

编程入门 行业动态 更新时间:2024-10-08 13:30:10
本文介绍了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 ++获得整数除法和余数的最佳方法

本文发布于:2023-11-29 09:06:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645956.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:余数   除法   整数   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!