Округлить число до заданного количества значащих цифр
Учитывая положительное число n (n> 1), округлите это число до заданного числа. значащих цифр, d.
Примеры:
Ввод: n = 139,59.
d = 4
Выход: число после округления - 139,6.
Число 139,59 состоит из 5 значащих цифр и для округления
число до 4 значащих цифр, 139,59 преобразуется в 139,6.
Ввод: n = 1240
d = 2
Выход: число после округления - 1200.Что такое значащие цифры?
Каждая из цифр числа, которые используются для его выражения с требуемой степенью точности, начиная с первой ненулевой цифры, называются значащими цифрами.
Поскольку есть числа с большим количеством цифр, например,
= 3,142857143, поэтому, чтобы ограничить такие числа управляемым количеством цифр, мы отбрасываем ненужные цифры, и этот процесс называется округлением .
Значащие цифры включают в себя все цифры числа, попадающие в одну из следующих категорий:
- Все ненулевые цифры.
- Нулевые цифры, которые-
- лежат между значащими цифрами.
- лежат справа от десятичной точки и одновременно справа от ненулевой цифры.
- особо обозначены как значимые.
В следующей таблице указаны номера и нет. присутствующих в них значащих цифр -

Правила округления числа
Чтобы округлить число до n значащих цифр -
- Удалите все цифры справа от n- й значащей цифры.
- Если это отброшенное число -
- меньше половины единицы в n- м месте, оставьте n- ю цифру без изменений.
- больше половины единицы в n- м месте, увеличьте n- ю цифру на единицу.
- ровно половину единицы на n- м месте, увеличьте n- ю цифру на единицу, если она нечетная, в противном случае оставьте ее без изменений.
В следующей таблице показано округление числа до заданного числа. значащих цифр -

C++
// C++ program to round-off a number to given no. of// significant digits#include <bits/stdc++.h>using namespace std;// Function to round - off the numbervoid Round_off(double N, double n){ int h; double l, a, b, c, d, e, i, j, m, f, g; b = N; c = floor(N); // Counting the no. of digits to the left of decimal point // in the given no. for (i = 0; b >= 1; ++i) b = b / 10; d = n - i; b = N; b = b * pow(10, d); e = b + 0.5; if ((float)e == (float)ceil(b)) { f = (ceil(b)); h = f - 2; if (h % 2 != 0) { e = e - 1; } } j = floor(e); m = pow(10, d); j = j / m; cout << "The number after rounding-off is " << j;}// Driver main functionint main(){ double N, n; // Number to be rounded - off N = 139.59; // No. of Significant digits required in the no. n = 4; Round_off(N, n); return 0;} |
Java
// Java program to round-off a number to given no. of// significant digitsimport java.io.*;import static java.lang.Math.*;public class A { // Function to round - off the number static void Round_off(double N, double n) { int h; double l, a, b, c, d, e, i, j, m, f, g; b = N; c = floor(N); // Counting the no. of digits to the left of decimal point // in the given no. for (i = 0; b >= 1; ++i) b = b / 10; d = n - i; b = N; b = b * pow(10, d); e = b + 0.5; if ((float)e == (float)ceil(b)) { f = (ceil(b)); h = (int)(f - 2); if (h % 2 != 0) { e = e - 1; } } j = floor(e); m = pow(10, d); j = j / m; System.out.println("The number after rounding-off is " + j); } // Driver main function public static void main(String args[]) { double N, n; // Number to be rounded - off N = 139.59; // No. of Significant digits required in the no. n = 4; Round_off(N, n); }} |
Python3
# Python 3 program to round-off a number# to given no. of significant digitsfrom math import ceil, floor, pow# Function to round - off the numberdef Round_off(N, n): b = N c = floor(N) # Counting the no. of digits # to the left of decimal point # in the given no. i = 0; while(b >= 1): b = b / 10 i = i + 1 d = n - i b = N b = b * pow(10, d) e = b + 0.5 if (float(e) == float(ceil(b))): f = (ceil(b)) h = f - 2 if (h % 2 != 0): e = e - 1 j = floor(e) m = pow(10, d) j = j / m print("The number after rounding-off is", j)# Driver Codeif __name__ == "__main__": # Number to be rounded - off N = 139.59 # No. of Significant digits # required in the no. n = 4 Round_off(N, n)# This code is contributed by# Surendra_Gangwar |
C#
// C# program to round-off a number// to given no. of significant digitsusing System;class A { // Function to round - off the number static void Round_off(double N, double n) { int h; double b, d, e, i, j, m, f; b = N; // c = Math.Floor(N); // Counting the no. of digits to the // left of decimal point in the given no. for (i = 0; b >= 1; ++i) b = b / 10; d = n - i; b = N; b = b * Math.Pow(10, d); e = b + 0.5; if ((float)e == (float)Math.Ceiling(b)) { f = (Math.Ceiling(b)); h = (int)(f - 2); if (h % 2 != 0) { e = e - 1; } } j = Math.Floor(e); m = Math.Pow(10, d); j = j / m; Console.WriteLine("The number after " + "rounding-off is " + j); } // Driver main function public static void Main() { double N, n; // Number to be rounded - off N = 139.59; // No. of Significant digits required in the no. n = 4; Round_off(N, n); }}// This code is contributed by vt_m. |
PHP
<?php// PHP program to round-off// a number to given no. of// significant digits// Function to round -// off the numberfunction Round_off($N, $n){ $h; $l; $a; $b; $c; $d; $e; $i; $j; $m; $f; $g; $b = $N; $c = floor($N); // Counting the no. of digits // to the left of decimal point // in the given no. for ($i = 0; $b >= 1; ++$i) $b = $b / 10; $d = $n - $i; $b = $N; $b = $b * pow(10, $d); $e = $b + 0.5; if ($e == ceil($b)) { $f = (ceil($b)); $h = $f - 2; if ($h % 2 != 0) { $e = $e - 1; } } $j = floor($e); $m = pow(10, $d); $j = $j / $m; echo "The number after rounding-off is " ,$j;} // Driver Code $N; $n; // Number to be rounded - off $N = 139.59; // No. of Significant digits // required in the no. $n = 4; Round_off($N, $n);// This code is contributed by anuj_67?> |
Javascript
<script>// Javascript program to round-off a number to given no. of// significant digitsimport// Function to round - off the numberfunction Round_off(N , n){ var h; var l, a, b, c, d, e, i, j, m, f, g; b = N; c = Math.floor(N); // Counting the no. of digits to the left of decimal point // in the given no. for (i = 0; b >= 1; ++i) b = parseInt(b / 10); d = n - i; b = N; b = b * Math.pow(10, d); e = b + 0.5; if (e == Math.ceil(b)) { f = (Math.ceil(b)); h = parseInt(f - 2); if (h % 2 != 0) { e = e - 1; } } j = Math.floor(e); m = Math.pow(10, d); j = j / m; document.write("The number after rounding-off is " + j);}// Driver main functionvar N, n;// Number to be rounded - offN = 139.59;// No. of Significant digits required in the no.n = 4;Round_off(N, n);// This code contributed by Princi Singh</script> |
Выход:
Число после округления - 139,6.
Эта статья предоставлена Мригендрой Сингхом . Если вам нравится GeeksforGeeks, и вы хотели бы внести свой вклад, вы также можете написать статью на сайте deposit.geeksforgeeks.org или отправить свою статью по электронной почте: grant@geeksforgeeks.org. Посмотрите, как ваша статья появляется на главной странице GeeksforGeeks, и помогите другим гикам.
Пожалуйста, напишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по теме, обсужденной выше.
Вниманию читателя! Не прекращайте учиться сейчас. Получите все важные математические концепции для соревновательного программирования с курсом Essential Maths for CP по доступной для студентов цене. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .