2016-12-17 12 views
0

私はdouble x = 23.456;と2つの整数dとcを与えられました。 私はdが値23を取得し、cは、私は、次の考え値456 なるように、それを破ることがあります: -小数点を2つの整数に分割する

int d; 
d=(int)x; 

それが整数であるように私はCをどうするかを考えることはできませんが私は

c=(x-d)*1000; 

を書く場合、それは他のケースのためだけではなく、この場合に適用できるかもしれません。

小数点以下の桁数を取得し、それに0を掛け算する方法はありますか? 助けてください!

+1

[小数点の取得](http://stackoverflow.com/questions/4427897/get-the-decimal-point) – IAmBlake

+0

重要な桁数は何ですか?小数部分が15桁の場合はどうなりますか?その15桁の値全体を保存しようとしていますか?これは次の質問につながります。あなたが解決しようとしている高レベルの問題は何ですか?分割する数字が必要ですか? – PaulMcKenzie

答えて

2

小数点以下が何もない限り、10で繰り返し掛けることができます。

double c = x - d; 

while(c - floor(c) > 0.0) 
{c *= 10;} 

あなたはまた、数を切り捨て床関数、のために#include <math.h>する必要があるかもしれません。例えばfloor(4.9)が返されます。4.0

+1

浮動小数点は近似値なので、非常に大きな 'c'が得られます。関連する質問については、http://stackoverflow.com/questions/41197139/how-to-find-digits-after-decimal#comment69594156_41197139を参照してください。 – Barmar

0

浮動小数点の計算は、C++ではちょっと難しいです(Javaや他の言語でも同じです)。あなたはそれらの直接比較を避け、それらを使用する際に、予測可能な結果を​​得るために、いくつかの他のものを行う、検討する必要があります。

私は2つのバリアントを提案することができ、問題の現実的な解決策については
double d1=1.1; 
double d2= d1/10.0; 

if(d2==0.11)cout << "equals" << endl; 
else cout << "not equals" << endl; //result is "not equals" 

d1=1.99; 
float f1=0.01f; 
double d3=d1+f1; 
if(d3==2.0)cout << "equals" << endl; 
else cout << "not equals" << endl; //result is "not equals" 

d1=1.99; 
d2=0.01; 
d3=d1+d2-2.0; 
if(d3==0.0)cout << "equals" << endl; 
else cout << "not equals" << endl; //result is "not equals" 

: ヴァール1は、その機能を使用することですこの問題を解決する

#include <iostream> 
#include <cmath> 

using namespace std; 


void split_double(const double value, int& i_part, int& r_part, 
        const int max_digits_after_dp, int min_digits_after_dp){ 


    auto powerOfTenL = [](int power){ int result = 1; 
     for(int i=0;i<power;++i)result *= 10; 
     return result; 
    }; 
    //Get integral part 
    i_part = (int)value; 
    double temp = (value-i_part); 
    double pOfTen = powerOfTenL(max_digits_after_dp); 
    temp *= pOfTen; 
    //Get real part 
    r_part = round(temp); 

    //Remove zeroes at the right in real part 
    int num_of_d = max_digits_after_dp; 
    if(min_digits_after_dp>max_digits_after_dp) 
     min_digits_after_dp=max_digits_after_dp; 
    while (num_of_d>min_digits_after_dp) { 
     //If the number is divisible by 10, divide it by 10 
     if(0==(r_part%10)) { r_part /=10; num_of_d--; 
     } 
     else break; //Last digit is not 0 
    } 
} 

int main(int argc, char *argv[]) 
{ 

    double value = 10.120019; 
    int ipart,rpart; 
    const int digitsMax = 6; 
    const int digitsMin = 3; 

    split_double(value,ipart,rpart,digitsMax,digitsMin); 
    cout<<"Double " <<value << " has integral part " <<ipart 
     <<" and real part "<<rpart<<endl; 

    return 0; 
} 

第二の変形例は、vsprintfのようなC/C++フォーマット関数を使用することであり、次いで、得られた文字列を分割:桁数を指定することを可能にします。

関連する問題