How to effectively deal with bots on your site? The best protection against click fraud.
Итак, мы открыли файл «new.cc» с инструкцией «nano». Этот файл создается с помощью «сенсорного» запроса оболочки. Теперь файл запускается в редакторе nano как пустой файл. Мы добавили заголовочный файл ввода-вывода «iostream» вверху. Библиотека iomanip была добавлена для использования метода setprecision() нашего кода. После этого мы использовали стандартное пространство имен «std», чтобы убедиться, что мы используем стандартный способ кода и синтаксиса. Весь код был выполнен внутри функции main() кода C++. Никакая другая определяемая пользователем функция для этой цели не используется.
В функции main() мы инициализировали переменную типа double «v» двойным значением. Первый стандартный оператор «cout» отображает фактическое значение двойной переменной «v» в оболочке без какого-либо обновления. После этого мы использовали 8 операторов cout, в каждом из которых применялся метод setprecision(). Это делается для того, чтобы каждый раз применять setprecision() к каждой переменной «v» с плавающей запятой. Вы должны понимать, что setprecision работает только со значением больше или равным 5. Если значение с плавающей запятой больше 5, оно увеличит значение перед ним.
Например, setprecision() для 1-го числа с плавающей запятой будет округлять «5» после точки, а значение «4» будет преобразовано в 5. Точно так же 2-е значение с плавающей запятой «2» не может быть округлено, 3-е значение с плавающей запятой «7» преобразует значение «2» в «3», 4-е значение с плавающей запятой «4» не может быть округлено, а 5-е значение с плавающей запятой «9» преобразует значение «4» в 5 перед ним. В точке «0» значение «4» будет преобразовано в 5. Отрицательная setprecision() ничего не делает, кроме отображения всего фактического значения. Все значения с плавающей запятой от 0 до 5 и -1, -2 будут отображаться после применения setprecision():
Пришло время скомпилировать и запустить код C++ setprecision с запросом на компиляцию g++ и запросом на выполнение «./a.out». Вывод показывает, что первая setprecision (1) преобразует 4 в 5. setprecision (2) ничего не сделал и отображает «4.5». setprecision (3) увеличил значение с «4,52» до «4,53». setprecision (4) ничего не делает со значением «4,527». setprecision (5) увеличивает значение с «4,5274» до «4,5275». setprecision (0) увеличил значение до 5. setprecision(-1) и setprecision(-2) ничего не сделали, как показано ниже:
Пример 02:
Давайте посмотрим на другой экземпляр. Код аналогичен приведенному выше примеру, но изменены только операторы cout. Первый cout показывает исходные значения, а следующие два показывают результат setprecision() с плавающей запятой 1 и 5. Последний cout отображает результат метода setprecision() с плавающей запятой 9, который физически недоступен. Результаты с плавающей запятой 1 и 5 вполне ожидаемы, но мы ничего не можем сказать о плавающей запятой 9. Давайте просто запустим файл и проверим, что выведет этот код:
с использованием пространство имен станд. ;
двойной в = 4.52749 ;
cout << «Значение перед установкой точности:» << в << ‘ \n ‘ ;
cout << установить точность ( 1 ) << «Вал в 1:» << в << ‘ \n ‘ ;
cout << установить точность ( 5 ) << «Вал в 5:» << в << ‘ \n ‘ ;
cout << установить точность ( 9 ) << «Вал в 9:» << в << ‘ \n ‘ ;
После компиляции и выполнения этого кода у нас есть очевидные результаты для setprecision в ячейках 1 и 3 значения с плавающей запятой «4,52749». Результат setprecision 9 показывает фактическое значение двойной переменной «v». Это может быть связано с тем, что значение для местоположения 9 не является фиксированным:
Давайте просто снова обновим код, чтобы исправить значения переменной «v». Итак, после того как первый оператор cout setprecision() был применен к 1-му местоположению переменной, мы использовали фиксированную переменную в cout:
с использованием пространство имен станд. ;
двойной в = 4.52749 ;
cout << «Значение перед установкой точности:» << в << ‘ \n ‘ ;
cout << установить точность ( 1 ) << «Вал в 1:» << в << ‘ \n ‘ ;
cout << установить точность ( 5 ) << «Вал в 5:» << в << ‘ \n ‘ ;
cout << установить точность ( 9 ) << «Вал в 9:» << в << ‘ \n ‘ ;
После компиляции и запуска этого обновленного кода у нас есть фиксированный результат setprecision в позиции 9 переменной «v», то есть 4,527490000:
Вывод:
Наконец, речь шла об использовании метода setprecision() в коде C++ для округления и отображения значения двойной переменной. Мы также объяснили фиксированные переменные в коде и их преимущества. Кроме того, мы реализовали два важных примера для объяснения концепции точности набора в C++. Мы надеемся, что вы нашли эту статью полезной. Дополнительные советы и руководства см. в других статьях Linux Hint.
C++ setprecision
By Afshan Banu
Introduction to C++ setprecision() Function
The setprecision is a manipulator function in C++ which is used to sets the decimal precision of floating-point values on output operations. This setprecision is the built-in function defined in <iomanip> header file in C++. The decimal number could contain an infinite length number which requires an infinite memory to store, but the decimal number is to be store in 4 or 8 bytes of memory. Hence some of the digits lost and store only a significant number of digits. Therefore to keep the significant number of digits without loss of information the precision of a floating-point number can be defined. If an inserted or extracted operator is modified the stream object and the concurrent access to the same stream object may create the data race condition. If the stream is in a valid state then an exception is thrown by setprecision() function.
Syntax of C++ setprecision
Below is the declaration of the setprecision() function in C++ is:
Web development, programming languages, Software testing & others
Parameters of C++ setprecision Function:
n – n is the int parameter which is specified the floating-point value decimal precision.
The return value of this function is not defined it just used as a manipulator for the stream.
Examples of setprecision() Function in C++
Below are the examples of C++ setprecision:
Example #1
We write the C++ code to understand the setprecision() function more clearly with the following example where we use setprecision() function used to set the different decimal number, as below:
Code:
Output:
As in the above code, the setprecision() function is used to set the different precision values for floating-point numbers like 0, 1, 2, 3, 4, -1, and -2. The positive precision numbers are working fine as we can see in the output, but the negative precision numbers are not working as expected it displaying in the default precision number that is 6.
Example #2
We write the C++ code to understand the setprecision() function where we display the default precision number, max precision number and then use the setprecision() function used to set the specific decimal precision number, as below:
Code:
Output:
As in the above code showing the default precision number, max precision number, and then set the specific precision number by using the setprecision() function. As in the output, we can see that the default precision number value is 6, the max precision number value is 8.
Example #3
We write the C++ code to understand the setprecision() function where we use the setprecision() function to set the specific decimal precision number and use the fixed to setup the decimal precision number fixed specified by the setprecision() function, as below:
Code:
Output:
As in the above code, the setprecision() function is used and set the precision values for the floating-point number to 7. Later in the code, the decimal number is printing which is printing the same as a store with the 4 decimal precision. And then in the code, the fixed-function is used which sets the floating-point values to fixed point notations as here it is set by the setprecision() function to 7, so now when the decimal number is printing, it is printing with the 7 fixed decimal precision.
Example #4
We write the C++ code to understand the setprecision() function where we use the setprecision() function to set the max decimal precision number and use the fixed to set up the max decimal precision number fixed specified by the setprecision() function, as below:
Code:
Output:
As in the above code, the setprecision() function is used and set the max precision values for floating-point number. when in the float number is printing it is printing with the default precision that is 4, but the float number is of a large number of precision value. So we can set the fixed precision number to the max by using the setprecision() function to the max, so now when the decimal number is printing, it is printing with all its decimal precision.
Conclusion
The setprecision() function is a built-in function and acts as a manipulator function in C++ which is used to sets the decimal precision of floating-point values on output operations. To use setprecision() function in a program we need to include the <iomanip> header file.
Recommended Article
This is a guide to C++ setprecision. Here we discuss the Introduction to C++ setprecision() Function and its Examples along with Code Implementation and Output. you can also go through our suggested articles to learn more –
Setprecision c что это
The decimal equivalent of 1/3 is 0.33333333333333…. An infinite length number would require infinite memory to store, and we typically have 4 or 8 bytes. Therefore, Floating point numbers store only a certain number of significant digits, and the rest are lost. The precision of a floating-point number defines how many significant digits it can represent without information loss. When outputting floating-point numbers, cout has a default precision of 6 and it truncates anything after that. Below are a few libraries and methods which are used to provide precision to floating-point numbers in C++:
1. floor() Method
Floor rounds off the given value to the closest integer which is less than the given value. It is defined in the <cmath> header file.
Time Complexity: O(1)
Auxiliary Space: O(1)
2. ceil() Method
Ceil rounds off the given value to the closest integer which is more than the given value. It is defined in the <cmath> header file.
Time Complexity: O(1)
Auxiliary Space: O(1)
3. trunc() Method
Trunc rounds remove digits after the decimal point. It is defined in the <cmath> header file.
Time Complexity: O(1)
Auxiliary Space: O(1)
4. round()
Rounds gave numbers to the closest integer. It is defined in the header files: <cmath> and <ctgmath>.
Time Complexity: O(1)
Auxiliary Space: O(1)
5. setprecision()
Setprecision when used along with ‘fixed’ provides precision to floating-point numbers correct to decimal numbers mentioned in the brackets of the setprecision. It is defined in header file <iomanip>.
Time Complexity: O(1)
Auxiliary Space: O(1)
Note: When the value mentioned in the setprecision() exceeds the number of floating point digits in the original number then 0 is appended to floating point digit to match the precision mentioned by the user.
Use setprecision in C++
This article will demonstrate multiple methods of how to use the setprecision method in C++.
Please enable JavaScript
Use setprecision() Method to Set Custom Precision for Floats
setprecision() is part of I/O manipulators library <iomanip> and can be used to modify default precision of the floating-point numbers. setprecision() is usually used in expressions with I/O streams.
The following example shows how to set float number precision for the cout output stream object. Notice that, setprecision() applies to the whole number (integer part and fractional part) and uses scientific notation when numbers have a bigger magnitude than the specified precision.
Use setprecision() and std::fixed() to Set Custom Precision for Floats
Alternatively, we can use setprecision() and fixed() stream manipulators in conjunction to print floating-point values with the same number of digits after the decimal point. The fixed() method sets the fractional part of the number to a fixed length, which by default is 6 digits. In the following code sample, we output to cout stream and call both manipulators before the number is inserted into the output.
Use setprecision() and std::fixed() to Align Floats to a Decimal Point
Finally, we can combine the setw , right , setfill , fixed and setprecision manipulators to output floating-point numbers aligned to the decimal point. setw method specifies the output stream width with the number of characters passed as an argument. setfill sets a character by which the unused space will be filled and right method tells cout the side to which filling operation applies.