فهرست منبع

add MY double to Rational

jezv 11 ماه پیش
والد
کامیت
9b5dbc27dd
3فایلهای تغییر یافته به همراه29 افزوده شده و 0 حذف شده
  1. 25 0
      Rational.cpp
  2. 1 0
      Rational.h
  3. 3 0
      main_rational.cpp

+ 25 - 0
Rational.cpp

@@ -39,6 +39,31 @@ Rational::Rational(float x)
     simple();
     simple();
 }
 }
 
 
+Rational::Rational(double x)
+{
+    const unsigned long long int bits = *(unsigned long long int*)(&x);
+    const unsigned long long int signBit = (bits >> 63) & 1;
+    const unsigned long long int exponentBits = (bits >> 52) & 0x7ff;
+    const unsigned long long int mantisBits = bits & 0xFFFFFFFFFFFFF;
+    unsigned long long int significant = (long long int)pow(2, 52) | mantisBits;
+
+    const long long int sign = signBit ? -1 : 1;
+
+    const long long int exp = exponentBits - 1023 - 52;
+
+    cout << bitset<64>(bits) << endl;
+    cout << bitset<64>(signBit) << endl;
+    cout << bitset<64>(exponentBits) << endl;
+    cout << bitset<64>(mantisBits) << endl;
+    cout << bitset<64>(pow(2,52)) << endl;
+    cout << bitset<64>(significant) << endl;
+    cout << bitset<64>(exp) << endl;
+
+    cout << setprecision(15) << fixed << sign * significant << '/' << (unsigned long long int)pow(2, -exp) << endl; 
+    cout << (sign * significant) / pow(2, -exp) << endl;
+    cout << sign * pow(2, -1022) * significant << endl;
+}
+
 Rational& Rational::operator += (const Rational& r)
 Rational& Rational::operator += (const Rational& r)
 {
 {
     int scm = lcm(denum, r.denum);
     int scm = lcm(denum, r.denum);

+ 1 - 0
Rational.h

@@ -13,6 +13,7 @@ public:
 
 
     Rational();
     Rational();
     Rational(float num);
     Rational(float num);
+    Rational(double num);
     Rational(int num1, int num2);
     Rational(int num1, int num2);
 
 
     Rational& operator *=(const Rational& r);
     Rational& operator *=(const Rational& r);

+ 3 - 0
main_rational.cpp

@@ -13,4 +13,7 @@ int main() {
     float x = float(63)/float(37);
     float x = float(63)/float(37);
     cout << x << endl;
     cout << x << endl;
     cout << Rational(x);
     cout << Rational(x);
+    double x2 = (double)63/(double)37;
+    cout << x2 << endl;
+    cout << Rational(x2);
 }
 }