Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to compute division upto n decimal places
Given with the value of x and y as a positive integer with the value of n for number of decimal places and the task is to generate the division up to n decimal places.
Example
Input-: x = 36, y = 7, n = 5 Output-: 5.14285 Input-: x = 22, y = 7, n = 10 Output-: 3.1428571428
Approach used in the below program is as follows −
- Input the value of a, b and n
- Check if b is 0 than division will go upto infinite and if a is 0 than result will be 0 as something divides to 0 is 0
- If n is greater than 1 than store the value of remainder and subtract it from the dividend after that multiply the result by ten. Start the next iteration
- Print the result
ALGORITHM
START Step 1-> declare function to compute division upto 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
5.14285
Advertisements