Перейти к содержимому

Math ceiling c что это

  • автор:

Math. Ceiling Метод

Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.

Возвращает наименьшее целое число, которое больше или равно указанному числу.

Перегрузки

Возвращает наименьшее целое число, которое больше или равно заданному десятичному числу.

Возвращает наименьшее целое число, которое больше или равно заданному числу с плавающей запятой двойной точности.

Комментарии

Поведение этого метода соответствует стандарту IEEE 754, раздел 4. Такое округление иногда называют округлением в сторону положительной бесконечности.

Ceiling(Decimal)

Возвращает наименьшее целое число, которое больше или равно заданному десятичному числу.

public: static System::Decimal Ceiling(System::Decimal d);
public static decimal Ceiling (decimal d);
static member Ceiling : decimal -> decimal
Public Shared Function Ceiling (d As Decimal) As Decimal
Параметры
Возвращаемое значение

Наименьшее целое число, которое больше или равно d . Обратите внимание, что данный метод возвращает не целочисленное значение, а значение типа Decimal.

Примеры

В следующем примере показан Math.Ceiling(Decimal) метод и он контрастирует с методом Floor(Decimal) .

decimal[] values = ; Console.WriteLine(" Value Ceiling Floor\n"); foreach (decimal value in values) Console.WriteLine("  ", value, Math.Ceiling(value), Math.Floor(value)); // The example displays the following output to the console: // Value Ceiling Floor // // 7.03 8 7 // 7.64 8 7 // 0.12 1 0 // -0.12 0 -1 // -7.1 -7 -8 // -7.6 -7 -8 
// The ceil and floor functions may be used instead. let values = [ 7.03m; 7.64m; 0.12m; -0.12m; -7.1m; -7.6m ] printfn " Value Ceiling Floor\n" for value in values do printfn $"  " // The example displays the following output to the console: // Value Ceiling Floor // // 7.03 8 7 // 7.64 8 7 // 0.12 1 0 // -0.12 0 -1 // -7.1 -7 -8 // -7.6 -7 -8 
Dim values() As Decimal = Console.WriteLine(" Value Ceiling Floor") Console.WriteLine() For Each value As Decimal In values Console.WriteLine("  ", _ value, Math.Ceiling(value), Math.Floor(value)) Next ' The example displays the following output to the console: ' Value Ceiling Floor ' ' 7.03 8 7 ' 7.64 8 7 ' 0.12 1 0 ' -0.12 0 -1 ' -7.1 -7 -8 ' -7.6 -7 -8 

Комментарии

Поведение этого метода соответствует стандарту IEEE 754, раздел 4. Такое округление иногда называют округлением в сторону положительной бесконечности. Иными словами, если d является положительным, то наличие любого дробного компонента приводит d к округлению до следующего наибольшего целого числа. Если d значение отрицательное, операция округления приводит к отмене любого дробного компонента d . Операция этого метода отличается от Floor(Decimal) метода , который поддерживает округление в сторону отрицательной бесконечности.

См. также раздел

Применяется к

Ceiling(Double)

Возвращает наименьшее целое число, которое больше или равно заданному числу с плавающей запятой двойной точности.

public: static double Ceiling(double a);
public static double Ceiling (double a);
static member Ceiling : double -> double
Public Shared Function Ceiling (a As Double) As Double
Параметры

Число двойной точности с плавающей запятой.

Возвращаемое значение

Наименьшее целое число, которое больше или равно a . Если значение параметра a равно NaN, NegativeInfinity или PositiveInfinity, возвращается это значение. Обратите внимание, что данный метод возвращает не целочисленное значение, а значение типа Double.

Примеры

В следующем примере показан Math.Ceiling(Double) метод и он контрастирует с методом Floor(Double) .

double[] values = ; Console.WriteLine(" Value Ceiling Floor\n"); foreach (double value in values) Console.WriteLine("  ", value, Math.Ceiling(value), Math.Floor(value)); // The example displays the following output to the console: // Value Ceiling Floor // // 7.03 8 7 // 7.64 8 7 // 0.12 1 0 // -0.12 0 -1 // -7.1 -7 -8 // -7.6 -7 -8 
// The ceil and floor functions may be used instead. let values = [ 7.03; 7.64; 0.12; -0.12; -7.1; -7.6 ] printfn " Value Ceiling Floor\n" for value in values do printfn $"  " // The example displays the following output to the console: // Value Ceiling Floor // // 7.03 8 7 // 7.64 8 7 // 0.12 1 0 // -0.12 0 -1 // -7.1 -7 -8 // -7.6 -7 -8 
Dim values() As Double = Console.WriteLine(" Value Ceiling Floor") Console.WriteLine() For Each value As Double In values Console.WriteLine("  ", _ value, Math.Ceiling(value), Math.Floor(value)) Next ' The example displays the following output to the console: ' Value Ceiling Floor ' ' 7.03 8 7 ' 7.64 8 7 ' 0.12 1 0 ' -0.12 0 -1 ' -7.1 -7 -8 ' -7.6 -7 -8 

Комментарии

Поведение этого метода соответствует стандарту IEEE 754, раздел 4. Такое округление иногда называют округлением в сторону положительной бесконечности. Иными словами, если a является положительным, то наличие любого дробного компонента приводит a к округлению до следующего наибольшего целого числа. Если a значение отрицательное, операция округления приводит к отмене любого дробного компонента a . Операция этого метода отличается от Floor(Double) метода , который поддерживает округление в сторону отрицательной бесконечности.

Начиная с Visual Basic 15.8, производительность преобразования double-to-integer оптимизирована при передаче значения, возвращаемого методом, в любую из функций целочисленного преобразования или если значение Double, возвращаемое , автоматически преобразуется в целое число с параметром Ceiling Ceiling Option Strict, равным Off. Эта оптимизация позволяет коду выполняться быстрее — до двух раз быстрее для кода, который выполняет большое количество преобразований в целочисленные типы. В следующем примере показаны такие оптимизированные преобразования:

Dim d1 As Double = 1043.75133 Dim i1 As Integer = CInt(Math.Ceiling(d1)) ' Result: 1044 Dim d2 As Double = 7968.4136 Dim i2 As Integer = CInt(Math.Ceiling(d2)) ' Result: 7969 

Math. Ceiling Method

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

Returns the smallest integral value greater than or equal to the specified number.

Overloads

Returns the smallest integral value that is greater than or equal to the specified decimal number.

Returns the smallest integral value that is greater than or equal to the specified double-precision floating-point number.

Remarks

The behavior of this method follows IEEE Standard 754, section 4. This kind of rounding is sometimes called rounding toward positive infinity.

Ceiling(Decimal)

Returns the smallest integral value that is greater than or equal to the specified decimal number.

public: static System::Decimal Ceiling(System::Decimal d);
public static decimal Ceiling (decimal d);
static member Ceiling : decimal -> decimal
Public Shared Function Ceiling (d As Decimal) As Decimal
Parameters

A decimal number.

Returns

The smallest integral value that is greater than or equal to d . Note that this method returns a Decimal instead of an integral type.

Examples

The following example illustrates the Math.Ceiling(Decimal) method and contrasts it with the Floor(Decimal) method.

decimal[] values = ; Console.WriteLine(" Value Ceiling Floor\n"); foreach (decimal value in values) Console.WriteLine("  ", value, Math.Ceiling(value), Math.Floor(value)); // The example displays the following output to the console: // Value Ceiling Floor // // 7.03 8 7 // 7.64 8 7 // 0.12 1 0 // -0.12 0 -1 // -7.1 -7 -8 // -7.6 -7 -8 
// The ceil and floor functions may be used instead. let values = [ 7.03m; 7.64m; 0.12m; -0.12m; -7.1m; -7.6m ] printfn " Value Ceiling Floor\n" for value in values do printfn $"  " // The example displays the following output to the console: // Value Ceiling Floor // // 7.03 8 7 // 7.64 8 7 // 0.12 1 0 // -0.12 0 -1 // -7.1 -7 -8 // -7.6 -7 -8 
Dim values() As Decimal = Console.WriteLine(" Value Ceiling Floor") Console.WriteLine() For Each value As Decimal In values Console.WriteLine("  ", _ value, Math.Ceiling(value), Math.Floor(value)) Next ' The example displays the following output to the console: ' Value Ceiling Floor ' ' 7.03 8 7 ' 7.64 8 7 ' 0.12 1 0 ' -0.12 0 -1 ' -7.1 -7 -8 ' -7.6 -7 -8 

Remarks

The behavior of this method follows IEEE Standard 754, section 4. This kind of rounding is sometimes called rounding toward positive infinity. In other words, if d is positive, the presence of any fractional component causes d to be rounded to the next highest integer. If d is negative, the rounding operation causes any fractional component of d to be discarded. The operation of this method differs from the Floor(Decimal) method, which supports rounding toward negative infinity.

See also

Applies to

Ceiling(Double)

Returns the smallest integral value that is greater than or equal to the specified double-precision floating-point number.

public: static double Ceiling(double a);
public static double Ceiling (double a);
static member Ceiling : double -> double
Public Shared Function Ceiling (a As Double) As Double
Parameters

A double-precision floating-point number.

Returns

The smallest integral value that is greater than or equal to a . If a is equal to NaN, NegativeInfinity, or PositiveInfinity, that value is returned. Note that this method returns a Double instead of an integral type.

Examples

The following example illustrates the Math.Ceiling(Double) method and contrasts it with the Floor(Double) method.

double[] values = ; Console.WriteLine(" Value Ceiling Floor\n"); foreach (double value in values) Console.WriteLine("  ", value, Math.Ceiling(value), Math.Floor(value)); // The example displays the following output to the console: // Value Ceiling Floor // // 7.03 8 7 // 7.64 8 7 // 0.12 1 0 // -0.12 0 -1 // -7.1 -7 -8 // -7.6 -7 -8 
// The ceil and floor functions may be used instead. let values = [ 7.03; 7.64; 0.12; -0.12; -7.1; -7.6 ] printfn " Value Ceiling Floor\n" for value in values do printfn $"  " // The example displays the following output to the console: // Value Ceiling Floor // // 7.03 8 7 // 7.64 8 7 // 0.12 1 0 // -0.12 0 -1 // -7.1 -7 -8 // -7.6 -7 -8 
Dim values() As Double = Console.WriteLine(" Value Ceiling Floor") Console.WriteLine() For Each value As Double In values Console.WriteLine("  ", _ value, Math.Ceiling(value), Math.Floor(value)) Next ' The example displays the following output to the console: ' Value Ceiling Floor ' ' 7.03 8 7 ' 7.64 8 7 ' 0.12 1 0 ' -0.12 0 -1 ' -7.1 -7 -8 ' -7.6 -7 -8 

Remarks

The behavior of this method follows IEEE Standard 754, section 4. This kind of rounding is sometimes called rounding toward positive infinity. In other words, if a is positive, the presence of any fractional component causes a to be rounded to the next highest integer. If a is negative, the rounding operation causes any fractional component of a to be discarded. The operation of this method differs from the Floor(Double) method, which supports rounding toward negative infinity.

Starting with Visual Basic 15.8, the performance of Double-to-integer conversion is optimized if you pass the value returned by the Ceiling method to the any of the integral conversion functions, or if the Double value returned by Ceiling is automatically converted to an integer with Option Strict set to Off. This optimization allows code to run faster — up to twice as fast for code that does a large number of conversions to integer types. The following example illustrates such optimized conversions:

Dim d1 As Double = 1043.75133 Dim i1 As Integer = CInt(Math.Ceiling(d1)) ' Result: 1044 Dim d2 As Double = 7968.4136 Dim i2 As Integer = CInt(Math.Ceiling(d2)) ' Result: 7969 

Учимся округлять в C#

А знаете ли вы, что Math.Round(1.5) == Math.Round(2.5) == 2 ? Можете ли сходу сказать, сколько будет -7%3 и 7%-3 ? Помните ли, чем отличаются Math.Round , Math.Floor , Math.Ceiling , Math.Truncate ? А как происходит округление при использовании string.Format ? Давайте немного погрузимся в мир округлений и разберёмся с нюансами, которые не для всех могут быть очевидными.

Math.Round

 Math.Round — это метод округления к ближайшему числу или к ближайшему числу с заданным количеством знаков после запятой. Работает с типами decimal и double , в параметрах можно встретить три вида параметров:
  • value : округляемое число
  • digits : количество знаков в дробной части, которые нужно оставить
  • mode : параметр, который определяет в какую сторону округлять число, которое находится ровно посередине между двумя вариантами

Параметр mode используется, когда округляемое значение находится ровно посередине между двумя вариантами. Принимает значение из следующего перечисления:

Обратите внимание, что по умолчанию mode == MidpointRounding.ToEven , поэтому Math.Round(1.5) == Math.Round(2.5) == 2 .

Math.Floor, Math.Ceiling, Math.Truncate

Сводная таблица

Сориентироваться в методах округления может помочь следующая табличка:

Округление проводится в соответствии со стандартом IEEE Standard 754, section 4.

Целочисленное деление и взятие по модулю

В C# есть два замечательных оператора над целыми числами: / для целочисленного деления (MSDN) и % для взятия остатка от деления (MSDN). Деление производится по следующим правилам:

  • При целочисленном делении результат всегда округляется по направлению к нулю.
  • При взятии остатка от деления должно выполняться следующее правило: x % y = x – (x / y) * y

Также можно пользоваться шпаргалкой:

string.Format

При форматировании чисел в виде строки можно пользоваться функцией string.Format (см. Standard Numeric Format Strings, Custom Numeric Format Strings). Например, для вывода числа с двумя знаками после десятичной точки можно воспользоваться string.Format(«», value) или string.Format(«», value) . Округление происходит по принципу AwayFromZero . Проиллюстрируем правила округления очередной табличкой:

", value) |       

Задачи

На приведённую тему есть две задачки в ProblemBook.NET: Rounding1, Rounding2.

  • GitHub
  • Twitter
  • RSS

Метод Math.ceil

Метод Math.ceil производит округление дробного числа до целого всегда в большую сторону.

Синтаксис

Math.ceil(число);

Пример

Округлим число 3.00001 в большую сторону:

console.log(Math.ceil(3.00001));

Результат выполнения кода:

Смотрите также

  • метод Math.floor ,
    который выполняет округление числа в меньшую сторону
  • метод Math.round ,
    который также выполняет округление числа до целого
  • методы toFixed и toPrecision ,
    которые также выполняют округление числа

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *