问题描述
我计划在游戏循环中使用此代码使用自定义位图字体绘制分数。
这就是我所拥有的。现在我知道我已经使用了模,除和幂运算符很多次了。我知道在游戏循环中使用它并不是一件好事。有什么建议吗?
// Get digit n,where n is digit starting from the units place and moving left
int getDigit(int number,int position)
{
return (number % (int)pow(10,position)) / pow(10,(position - 1));
}
解决方法
如果int
是32位,则:
static const int table[] =
{ 1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000 };
return number / table[position-1] % 10;
是一个合理的实现:
- 它不会调用
pow
或使用浮点运算。 - 它使用一个表查找,一个变量除法和一个带有常数的余数运算(编译器可以将其优化为一个乘法,并进行一些移位和加法运算)。
(请注意,position
在表查找中被调整为基于一的值,以匹配问题中的代码,但是通常的做法是将单位位置称为位置0,而不是位置1。)>
如果要提取多个位置或整数的数字,则应考虑其他实现方式。
,您说您提取数字以显示游戏分数;所以我假设您将使用整个原始号码。
您可以这样循环提取所有数字:
int number = 1234; // this variable will be consumed
while (number) {
rightmostdigit = number % 10;
// do something with the extracted digit
number /= 10; // discard the rightmost at go to the next
}
上面的例程从右边提取数字,因此分数应从右到左绘制。警告如果数字为零,则永远不会执行循环...
如果您想从左侧提取数字并假设固定长度的分数(例如“ 00123”),则可以将单个数字存储在数组中,然后以相反的方向读回它们:它应该比尝试更快从左到右提取数字。