Advertisement
jasonpogi1669

Truncate up to 'n' Decimal Places Manually using C++

Jul 24th, 2021
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int main() {
  6.     cout << "--------------------------------------------\n";
  7.     cout << "Enter a PROPER fraction\n";
  8.     cout << "[Numerator MUST be smaller than Denominator]\n";
  9.     cout << "--------------------------------------------\n";
  10.     cout << "Enter numerator: ";
  11.     int x;
  12.     cin >> x;
  13.     cout << "Enter denominator: ";
  14.     int y;
  15.     cin >> y;
  16.     cout << "--------------------------------------------\n";
  17.     cout << "Fraction = " << x << " / " << y << '\n';
  18.     cout << "--------------------------------------------\n";
  19.     cout << "Enter number of decimal places to TRUNCATE: ";
  20.     int n;
  21.     cin >> n;
  22.     x *= 10;
  23.     int cnt = 0;
  24.     vector<int> decimals;
  25.     while (cnt < n) {
  26.         int quotient = x / y;
  27.         decimals.emplace_back(quotient);
  28.         x -= (y * quotient);
  29.         x *= 10;
  30.         cnt++;
  31.     }
  32.     cout << "--------------------------------------------\n";
  33.     cout << "After TRUNCATING " << n << " decimal places:\n";
  34.     cout << "0.";
  35.     for (int i = 0; i < (int) decimals.size(); i++) {
  36.         cout << decimals[i];
  37.     }
  38.     cout << '\n';
  39.     return 0;
  40. }
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement