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

C ++소수점 n 자리까지 계산할 수 있는 프로그램

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

예제

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

the method used in the following program is as follows-

  • input 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 than1,then store the value of the remainder, then subtract it from the divisor, then multiply by ten. Start the next iteration

  • print the result

algorithm

START
단계 1-> declare function to compute division upto n decimal places
   void compute_division(int a, int b, int n)
   check IF (b == 0)
      Infinite 출력
   끝
   IF(a == 0) 확인
      0 출력
   끝
   IF(n <= 0) 확인
      a 출력/b
   끝
   IF(((a > 0) && (b < 0)) || ((a < 0) && (b > 0))) 확인
      print "-"
      a를 설정 -a
      b를 설정 -b
   끝
   int dec를 선언하고 설정 / b
   Loop For int i = 0 and i <= n and i++
      dec 출력
      a = a 설정 - (b * dec)
      IF(a == 0)
         break;
      끝
      a = a 설정 * 10
      dec = a 설정 / b
      IF(i == 0)
         "." 출력
      끝
   끝
단계 2-> 메인 함수 내에서
   int a를 선언하고 설정 36, b = 7, n = 5
   compute_division(a, b, n) 호출
STOP

예제

#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;
}

출력 결과

5.14285