这里是说运算结果保留两位小数, 不是说输出结果保留两位小数,如果是输出的话,直接printf("%.2f")就行了。
#include <stdio.h> int main() { // 四舍五入 double sp = 36.51647; sp = ((double)((int)((sp + 0.005) * 100))) / 100; printf("sp: %lf ", sp); // 直接舍入 double vp = 36.51647; vp = ((double)((int)(vp * 100))) / 100.0; printf("vp: %lf ", vp); return 0; }
运行结果:
sp: 36.520000
vp: 36.510000
参考链接:
1. https://www.cnblogs.com/airduce/p/9708795.html
2. https://www.cnblogs.com/2014acm/p/3887393.html