C语言四舍五入保留一位小数
时间: 2023-09-11 12:03:58 浏览: 132
要在C语言中实现四舍五入并保留一位小数,可以使用以下代码:
```c
#include <stdio.h>
int main() {
double num;
scanf("%lf", &num);
num = (int)(num * 10 + 0.5) / 10.0;
printf("%.1lf\n", num);
return 0;
}
```
这段代码首先使用`scanf`函数来获取用户输入的浮点数。然后将这个浮点数乘以10,并加上0.5来实现四舍五入的效果。接着,将结果转换为整数类型,再除以10.0来保留一位小数。最后,使用`printf`函数来输出结果,使用"%.1lf"格式来保留一位小数。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [c语言四舍五入保留小数](https://blog.csdn.net/qq_64061494/article/details/127132103)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [c语言中如何进行四舍五入?](https://blog.csdn.net/unityFengYue/article/details/124208823)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文