假设我有一个像 134658 这样的数字,我想要第 3 个数字(百位),即“6”。
在Objective-C中得到它的最短长度代码是多少?
这是我当前的代码:
int theNumber = 204398234;
int theDigitPlace = 3;//hundreds place
int theDigit = (int)floorf((float)((10)*((((float)theNumber)/(pow(10, theDigitPlace)))-(floorf(((float)theNumber)/(pow(10, theDigitPlace)))))));
//Returns "2"
最佳答案
可能有更好的解决方案,但这个稍微短一些:
int theNumber = 204398234;
int theDigitPlace = 3;//hundreds place
int theDigit = (theNumber/(int)(pow(10, theDigitPlace - 1))) % 10;
在您的情况下,它将数字除以 100 得到 2043982,然后“提取”
带有“余数运算符”%
的最后一位十进制数字。
备注:该解决方案假设 pow(10, theDigitPlace - 1)
的结果是
精确的。这是有效的,因为 double
在 iOS 上有大约 16 位有效的十进制数字和 int
是一个 32 位数字,最多有 10 位小数。
关于ios - 从值中获取数字的最短方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23205384/