Lab 2-5: 大正實數乘法 (10%)

  • 輸入:兩正實數的整數部分、正實數的小數部分(輸入數字乘以\( \frac{1}{1,000,000,000} \)),整數及小數各不超過 9 位數字
  • 輸出:兩正實數數值、兩正實數的積,整數及小數各不超過 18 位數字,小數部分固定顯示 18 位。
  • 檔名:lab2_5_<學號>.cpp (e.g. lab2_5_106062802.cpp)

程式需提示使用者輸入兩正實數的整數部分、正實數的小數部分,程式需輸出兩正實數數值、兩正實數的積。

Format

Input real number (a), before decimal point: <(a) before decimal point>⏎
Input real number (a), after decimal point: <(a) after decimal point>⏎
The real number (a) is: <real number (a)>
Input real number (b), before decimal point: <(b) before decimal point>⏎
Input real number (b), after decimal point: <(b) after decimal point>⏎
The real number (b) is: <real number (b)>
(a) * (b) = <real number (a) * (b)>

Example

$ ./a.out
Input real number (a), before decimal point: 123456789⏎
Input real number (a), after decimal point: 123456789⏎
The real number (a) is: 123456789.123456789000000000
Input real number (b), before decimal point: 987654321⏎
Input real number (b), after decimal point: 987654321⏎
The real number (b) is: 987654321.987654321000000000
(a) * (b) = 121932631356500531.347203169112635269

$ ./a.out
Input real number (a), before decimal point: 1⏎
Input real number (a), after decimal point: 1⏎
The real number (a) is: 1.000000001000000000
Input real number (b), before decimal point: 2⏎
Input real number (b), after decimal point: 2⏎
The real number (b) is: 2.000000002000000000
(a) * (b) = 2.000000004000000002

Reference:

Reference Code:

Credit: 金昆樂 (110021111)

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    long long int a1 = 0, a2 = 0, b1 = 0, b2 = 0;
    cout << "Input real number (a), before decimal point: ";
    cin >> a1;
    cout << "Input real number (a), after decimal point: ";
    cin >> a2;
    cout << "The real number (a) is: " << a1 << "."
         << setfill('0') << setw(9) << a2 << "000000000" << endl;
    cout << "Input real number (b), before decimal point: ";
    cin >> b1;
    cout << "Input real number (b), after decimal point: ";
    cin >> b2;
    cout << "The real number (b) is: " << b1 << "."
         << setfill('0') << setw(9) << b2 << "000000000" << endl;
    long long int N = 1000000000;
    long long int c1 = a1 * b1 + a1 * b2 / N + a2 * b1 / N;
    long long int c2 = a2 * b2 + ((a1 * b2) % N) * N + ((a2 * b1) % N) * N;
    c1 += c2 / (N * N);
    c2 = c2 % (N * N);
    cout << "(a) * (b) = " << c1 << '.'
         << setfill('0') << setw(18) << c2 << endl;
    return 0;
}