Home  >  Article  >  Backend Development  >  How to keep two decimal places in C language

How to keep two decimal places in C language

下次还敢
下次还敢Original
2024-04-27 22:15:531236browse

In C language, to retain two decimal places, you can: declare a floating-point variable. Use the printf() function to print floating point variables. Use the %.2f format specifier in the format string.

How to keep two decimal places in C language

How to retain two decimal places in C language

In C language, you can use printf () function and specify the decimal digit format to retain two decimal places.

Specific steps:

  1. Use floating-point variables:
    Declare a floating-point variable to store decimals to be retained number.
  2. Use the printf() function:
    Use the printf() function to print floating point variables.
  3. Specify the decimal digit format:
    In the format string of the printf() function, use the %.2f format specifier. This will preserve two decimal places.

Sample code:

<code class="c">#include <stdio.h>

int main() {
  float number = 3.14159265;  // 浮点型变量
  printf("%.2f", number);  // 输出保留两位小数

  return 0;
}</code>

Output:

<code>3.14</code>

In this example, although number The value of the variable has 9 decimal places, but the printf("%.2f", number) statement will truncate the output to two decimal places, which is <code>3.14</code>.

The above is the detailed content of How to keep two decimal places in C language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn