四舍六入五成双

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include "../apue.2e/include/apue.h"
 
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <assert.h>
#include <string.h>
#include <limits.h>
 
void test_1(void)
{
	/*
	四舍六入五成双规则:
	对于位数很多的近似数,当有效位数确定后,其后面多余的数字应该舍去,只保留有效数字最末一位,
	这种修约(舍入)规则是“四舍六入五成双”,也即“4舍6入5凑偶”这里“四”是指≤4 时舍去,
	"六"是指≥6时进上,"五"指的是根据5后面的数字来定,当5后有有效数时(cc_1/cc_2),舍5入1;当5后无有效数字
	时(bb_1/bb_2),需要分两种情况来讲:①5前为 奇数,舍5入1;②5前为偶数,舍5不进。(0是 偶数)
	下面举例,用上述规则对下列数据保留3位有效数字:
	*/
	float aa_1 = 9.8249;	// 9.82
	float aa_2 = 9.82671;	// 9.83
 
	float bb_1 = 9.8250;	// 9.82
	float bb_2 = 9.8350;	// 9.84
 
	float cc_1 = 9.8351;	// 9.84
	float cc_2 = 9.82501;	// 9.83
 
	printf("%.2f\n", aa_1);
	printf("%.2f\n", aa_2);
	printf("%.2f\n", bb_1);
	printf("%.2f\n", bb_2);
	printf("%.2f\n", cc_1);
	printf("%.2f\n", cc_2);
 
	printf("===================\n");
 
	char xx_1[8];
	char xx_2[8];
 
	char yy_1[8];
	char yy_2[8];
 
	char zz_1[8];
	char zz_2[8];
 
	sprintf(xx_1, "%.2f\n", aa_1);
	sprintf(xx_2, "%.2f\n", aa_2);
	sprintf(yy_1, "%.2f\n", bb_1);
	sprintf(yy_2, "%.2f\n", bb_2);
	sprintf(zz_1, "%.2f\n", cc_1);
	sprintf(zz_2, "%.2f\n", cc_2);
 
	printf("%s", xx_1);
	printf("%s", xx_2);
	printf("%s", yy_1);
	printf("%s", yy_2);
	printf("%s", zz_1);
	printf("%s", zz_2);

	printf("===================\n");

	float aa_1_ = atof(xx_1);
	float aa_2_ = atof(xx_2);
	float bb_1_ = atof(yy_1);
	float bb_2_ = atof(yy_2);
	float cc_1_ = atof(zz_1);
	float cc_2_ = atof(zz_2);

 	printf("%f\n", aa_1_);
	printf("%f\n", aa_2_);
	printf("%f\n", bb_1_);
	printf("%f\n", bb_2_);
	printf("%f\n", cc_1_);
	printf("%f\n", cc_2_);
}
 
int main(int argc, char* argv[])
{
	test_1();
	return 0;
}

输出结果:

9.82
9.83
9.82
9.84
9.84
9.83
===================
9.82
9.83
9.82
9.84
9.84
9.83
===================
9.820000
9.830000
9.820000
9.840000
9.840000
9.830000

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值