本文介绍了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
)。
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.
int c = (int)a / b;
int d = a % b; /* Likely uses the result of the division. */
这篇关于C ++获得整数除法和余数的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!