C ++查找功率和数字的绝对值

时间:2015-04-12 17:10:58

标签: c++ math

我有以下数字的数字:

1). 3.1456e10
2). 56.7
3). 1.62166e+15
4). 1.9651e+87
5). 335544.32e+10

现在,我希望将这些数字乘以10,直到e(即10 ^)最多为255且至少为0.而且“e”之前的数字最多为2 ^ 24。 例如。对于上述数字,我想表达为:

1). 3.1456e10= 31456e6 (before_e: 31456, after_e: 6)
2). 56.7 = 56.7 (before_e: 56, after_e: 0)
3). 1.62166e+15 = 162166e+10 (before_e:162166, after_e: 10)
4). 1.9651e+87= 19651e+83 (before_e:19651, after_e:83)
5). 335544.32e+10=3355443 (before_e:3355443, after_e:9)

我知道我可以保持数字倍增,直到它们小于2 ^ 24。但是如何在C ++中找出“e”之后的数字。因此,我无法理解如何使用C ++程序找到before_e和after_e的值。

2 个答案:

答案 0 :(得分:1)

这是一个简单的算法,用于获得正数x的所需表示:

  1. 如果x > 1e255,请计算y = x / 1e255并打印y * 1e255y以定点表示法打印)。
  2. 否则,如果x < 1打印x * 1e0x以定点表示法打印)。
  3. 否则以标准十进制科学记数法打印x

答案 1 :(得分:1)

此代码应该完全符合您的要求:

#include <iostream>

using namespace std;

int main()
{
double a = 335544.32e+10; //arbitrary testing number
cout << a << endl; 
int after_e = 0;
//now checks if the number is divisible by ten, and the length of the exponent
while((long)a%10==0&&after_e<256){
   a = a/10; //removes a multiplication by 10
   after_e++;//increments the exponent variable
}
long before_e = (long)a;
//follows the constraint of before_e being less than 2^24, and truncates the rest of the number
while(before_e>16777216){
   before_e /= 10;
   after_e++;
}
cout<<"before_e "<<before_e<<" , "<<"after_e "<<after_e<<endl;
return 0;
}