如何在C语言中截断小数位数(不四舍五入)?代码问题求助
实现C语言中小数的截断(而非四舍五入)输出
问题场景
现有计算餐费小费与税费的C代码:
#include "cs50.h" #include <stdio.h> int main() { float charge = get_float("Enter the charge for food: "); float tip = charge/100 * 18; printf("Tip: $%.2f\n", tip); float tax = charge/100 * 7; printf("Tax: $%.2f\n", tax); float total = charge + tip + tax; printf("Total: $%.2f", total); }
当输入餐费78.5时,税费计算结果为5.495,但printf的%.2f格式会自动四舍五入输出为5.50,需求是直接截断第二位小数后的部分,保留5.49这类结果。
解决方法
方法1:整数运算截断
核心思路是将浮点数放大100倍转换为整数(整数转换会直接截断小数部分),再转回浮点数缩小100倍,实现截断效果:
#include "cs50.h" #include <stdio.h> int main() { float charge = get_float("Enter the charge for food: "); // 截断小费到两位小数 float tip = (int)(charge * 18) / 100.0; printf("Tip: $%.2f\n", tip); // 截断税费到两位小数 float tax = (int)(charge * 7) / 100.0; printf("Tax: $%.2f\n", tax); // 计算总费用并截断 float total = charge + tip + tax; total = (int)(total * 100) / 100.0; printf("Total: $%.2f", total); }
输入78.5时,charge*7得到549.5,转换为int后变为549,除以100.0得到5.49,实现了截断输出。
方法2:使用floor函数
借助<math.h>中的floor函数,该函数会返回不大于输入值的最大整数,对正数而言等价于截断小数部分:
#include "cs50.h" #include <stdio.h> #include <math.h> int main() { float charge = get_float("Enter the charge for food: "); float tip = floor(charge * 18) / 100.0; printf("Tip: $%.2f\n", tip); float tax = floor(charge * 7) / 100.0; printf("Tax: $%.2f\n", tax); float total = charge + tip + tax; total = floor(total * 100) / 100.0; printf("Total: $%.2f", total); }
注意:编译时需要链接数学库,比如使用gcc filename.c -o filename -lm命令(在线GDB环境通常已自动处理)。
内容的提问来源于stack exchange,提问作者might be andrew
相关产品推荐
相关产品推荐

