C 语言如何保留两位小数
在 C 语言中,可以通过以下方法保留两位小数:
1. 使用 printf() 函数
<code class="c">printf("%.2f", number);</code>其中,
number是要保留两位小数的数字,
%.2f指定要保留两位小数并使用浮点格式输出。
立即学习“C语言免费学习笔记(深入)”;
2. 使用 round() 函数
<code class="c">number = round(number * 100) / 100;</code>
round()函数将数字四舍五入到最接近的整数。将其乘以 100 并除以 100 可保留两位小数。
3. 使用 fixed-point 算术
<code class="c">fixed_point_number = (int)(number * 100);</code>
这种方法将数字乘以 100,然后将其转换为整数。这会保留两位小数的精度,因为 100 的倍数中的小数点会被截断。
例子
例如,要将浮点数 3.141592 保留两位小数,可以使用以下代码:
<code class="c">printf("%.2f\n", 3.141592); // 输出 3.14</code> 