Lab 2-4: 大正實數加法 (10%)
- 輸入:兩正實數的整數部分、正實數的小數部分(輸入數字乘以\( \frac{1}{1,000,000,000,000,000,000} \)),整數及小數各不超過 18 位數字
- 輸出:兩正實數數值、兩正實數的和,整數不超過 19 位數字,小數部分固定顯示 18 位。
- 檔名:lab2_4_<學號>.cpp (e.g. lab2_4_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: 123456789012345678⏎
Input real number (a), after decimal point: 123456789012345678⏎
The real number (a) is: 123456789012345678.123456789012345678
Input real number (b), before decimal point: 987654321098765432⏎
Input real number (b), after decimal point: 987654321098765432⏎
The real number (b) is: 987654321098765432.987654321098765432
(a) + (b) = 1111111110111111111.111111110111111110
$ ./a.out
Input real number (a), before decimal point: 1⏎
Input real number (a), after decimal point: 1⏎
The real number (a) is: 1.000000000000000001
Input real number (b), before decimal point: 2⏎
Input real number (b), after decimal point: 2⏎
The real number (b) is: 2.000000000000000002
(a) + (b) = 3.000000000000000003
Reference:
Reference Code:
Credit: 金昆樂 (110021111)
#include <iostream>
#include <iomanip>
#include <cmath>
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(18) << a2 << 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(18) << b2 << endl;
long long int c2 = a2 + b2, c1 = a1 + b1;
long long int N = 1000000000000000000;
if (c2 >= N)
{
c2 = c2 - N;
c1++;
}
cout << "(a) + (b) = " << c1 << '.'
<< setfill('0') << setw(18) << c2 << endl;
return 0;
}