English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C ++Program can calculate decimal places up to n

Given that x and y are positive integers, n is the number of decimal places, the task is to generate the division result with n decimal places.

Example

Input-: x = 36, y = 7, n = 5
Output-: 5.14285
Input-: x = 22, y = 7, n = 10
Output-: 3.1428571428

The methods used in the following program are as follows-

  • Enter the values of a, b, and n

  • Check if b is 0, then the division will be infinite; if a is 0, then the result will be 0, because something divided by 0 is 0

  • If n is greater than1Store the value of the remainder, then subtract it from the divisor, and then multiply by ten. Start the next iteration

  • Print the result

Algorithm

START
Step 1-declare function to compute division up to n decimal places
   void compute_division(int a, int b, int n)
   check IF (b == 0)
      print "Infinite"
   End
   check IF(a == 0)
      print 0
   End
   check IF(n <= 0)
      print a/b
   End
   check IF(((a > 0) && (b < 0)) || ((a < 0) && (b > 0)))
      print "-"
      set a = a > 0 ? a : -a
      set b = b > 0 ? b : -b
   End
   Declare and set int dec = a / b
   Loop For int i = 0 and i <= n and i++
      print dec
      Set a = a - (b * dec)
      IF(a == 0)
         break
      End
      Set a = a * 10
      set dec = a / b
      IF (i == 0)
         print "."
      End
   End
Step 2-> In main()
   Declare and set int a = 36, b = 7, n = 5
   Call compute_division(a, b, n)
STOP

Example

#include <bits/stdc++.h>
using namespace std;
void compute_division(int a, int b, int n) {
    if (b == 0) {
        cout << "Infinite" << endl;
        return;
    }
    if (a == 0) {
        cout << 0 << endl;
        return;
    }
    if (n <= 0) {
        cout << a / b << endl;
        return;
    }
    if (((a > 0) && (b < 0)) || ((a < 0) && (b > 0))) {
        cout << ";"-";
        a = a > 0 ? a : -a;
        b = b > 0 ? b : -b;
    }
    int dec = a / b;
    for (int i = 0; i <= n; i++) {
        cout << dec;
        a = a - (b * dec);
        if (a == 0)
            break;
        a = a * 10;
        dec = a / b;
        if (i == 0)
            cout << ".";
    }
}
int main() {
    int a = 36, b = 7, n = 5;
    compute_division(a, b, n);
    return 0;
}

Output Result

5.14285