[英]How to convert string representation of an arbitrary length integer in a given base to decimal?
[英]How to create a float given an integer and the place of the decimal?
給定整數和小數位,如何生成浮點數?
例如:
int decimal = 1000;
int decimal_position = 3;
float value = 1.000;
我已經通過使用權力實現了這一點,但這效率不高
decimal/pow(10, decimal_position)
你可以用幾個整數乘法和一個浮點除法來做到這一點:
int decimal = 1000;
int decimal_position = 3;
int offset = 1, i;
for (i=0; i<decimal_position; i++) {
offset *= 10;
}
float value = (float)decimal / offset;
請注意,假設decimal_position
為非負且 10 decimal_position適合int
。
給定整數和小數位,如何生成浮點數?
我已經通過使用權力實現了這一點,但這效率不高
float value = decimal/pow(10, decimal_position);
這取決於decimal_position
的范圍。
當0 <= decimal_position < 8
,代碼可以使用查表。
const float tens[8] = { 1.0f, 0.1f, ..., 1.0e-7f };
float value = decimal*tens[decimal_position];
然而要處理所有導致有限值的int decimal
和int decimal_position
,使用float powf(float )
而不是double pow(double)
應該是首選。
// float power function
float value = decimal/powf(10.0f, decimal_position);
如果不需要最佳值,代碼可以*
。 這稍微不那么精確,因為0.1f
不完全是數學 0.1。 然而*
通常比/
快。
float value = decimal*powf(0.1f, decimal_position);
循環以避免powf()
可以為decimal_position
小值完成
if (decimal_position < 0) {
if (decimal_position > -N) {
float ten = 1.0f;
while (++decimal_position < 0) ten *= 10.0f;
value = decimal*ten;
while (++decimal_position < 0) value /= 10.0f; // or value *= 0.1f;
} else {
value = decimal*powf(10.0f, -decimal_position);
}
} else {
if (decimal_position < N) {
float ten = 1.0f;
while (decimal_position-- > 0) ten *= 10.0f;
value = decimal/ten;
} else {
value = decimal/powf(10.0f, decimal_position); // alternate: *powf(0.1f, ...
}
}
選擇處理器可能會受益於使用pow()
與powf()
,但我發現powf()
通常更快。
當然,如果int decimal
和int decimal_position
使得整數答案是可能的:
// example, assume 32-bit `int`
if (decimal_position <= 0 && decimal_position >= -9) {
const long long[10] = {1,10,100,1000,..., 1000000000};
value = decimal*i_ten[-decimal_position];
} else {
value = use above code ...
或者如果abs(decimal_position) <= 19
並且 FP 數學很昂貴,請考慮:
unsigned long long ipow10(unsigned expo) {
unsigned long long ten = 10;
unsigned long long y = 1;
while (expo > 0) {
if (expo % 2u) {
y = ten * y;
}
expo /= 2u;
x *= ten;
}
return y;
}
if (decimal_position <= 0) {
value = 1.0f*decimal*ipow10(-decimal_position);
} else {
value = 1.0f*decimal/ipow10(decimal_position);
}
或者如果abs(decimal_position) <= 27
...
if (decimal_position <= 0) {
value = scalbnf(decimal, -decimal_position) * ipow5(-decimal_position);
} else {
value = scalbnf(decimal, -decimal_position) / ipow5(decimal_position);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.