Home > Article > Backend Development > How to retain 1 decimal place in C language
In C language, the methods of retaining one decimal place are: 1. Use a fixed decimal point to format "%.1f"; 2. Use the round() function to round to one decimal place; 3. Use customization Format specifications to one decimal place.
How to retain one decimal place in C language
In C language, retaining one decimal place can be used The following methods:
1. Use fixed decimal point formatting:
<code class="c">#include <stdio.h> int main() { float number = 123.456; // 使用 "%.1f" 格式化指定保留一位小数 printf("%.1f\n", number); // 输出:123.5 return 0; }</code>
2. Use the round() function:
<code class="c">#include <math.h> int main() { float number = 123.456; // 使用 round() 函数四舍五入到一位小数 number = roundf(number * 10) / 10; printf("%.1f\n", number); // 输出:123.5 return 0; }</code>
3. Use customized formatting:
<code class="c">#include <stdio.h> int main() { float number = 123.456; char format[] = "%.1f"; printf(format, number); // 输出:123.5 return 0; }</code>
Among the above methods, using fixed decimal point formatting is the simplest method because it does not require additional library functions or customized formatting operate.
Note:
The above is the detailed content of How to retain 1 decimal place in C language. For more information, please follow other related articles on the PHP Chinese website!