将十进制数分解为幂和系数

时间:2016-03-15 14:02:38

标签: c++ decimal

如何在c ++函数中将十进制数分解为十的幂后获得幂和系数?我希望得到以下内容。

void getPowerTen (double a, vector<int>& coef, vector<int>& power)
{
    //20.47 = 2x10^1 + 0x10^0 + 4x10^-1 + 7x10^-2

    //n_power = 4;
    //coef.resize(n_power);
    //power.resize(n_power);

    //coef[0] = 2;
    //coef[1] = 0;
    //coef[2] = 4;
    //coef[3] = 7;

    //power[0] = 1;
    //power[1] = 0;
    //power[2] = -1;
    //power[3] = -2;
}

1 个答案:

答案 0 :(得分:0)

#include <iostream>
#include <vector>
#include <cmath>
#include <sstream>

using namespace std;

void getPowerTen (double a)
{
    //20.47 = 2x10^1 + 0x10^0 + 4x10^-1 + 7x10^-2

    //n_power = 4;
    //coef.resize(n_power);
    //power.resize(n_power);

    //coef[0] = 2;
    //coef[1] = 0;
    //coef[2] = 4;
    //coef[3] = 7;

    //power[0] = 1;
    //power[1] = 0;
    //power[2] = -1;
    //power[3] = -2;

    int n = a;
    double d = a-n;
    vector<int> C, P;

    ostringstream strs;                         // To COnvert Double into String
    strs << a;
    string number = strs.str();
    int p;
    for(int i=0; i<number.length(); i++){           // Getting Highest Power for Integer Part
        if(number[i]=='.'){
            p = i - 1;
            break;
        }
    }


    for(int i=0; i<number.length(); i++){
        if(number[i] == '.')
            p = -1 ;


        if(number[i] >= 48 && number[i] <= 57){
            int b = number[i] - 48 ;
            C.push_back(b%(10 ^ p));
            P.push_back(p);

            p--;
        }
    }

    for(int i=0; i<C.size(); i++){
        cout<<"Coeff = "<<C[i]<<" power = "<<P[i]<<endl;
    }


}
int main(){

    getPowerTen(20.47);
    return 0;
}

步骤:

1 - &gt;将Double转换为字符串

2 - &gt;获得整数部分的最高权力

3 - &gt;遍历字符串并逐个获取每个数字,并降低功率

4 - &gt;如果&#39;。&#39;浮动部分开始,将功率设置为-1

Vector C代表Coefficient&amp; P的功率为10