double类型的变量保留两位第三位四舍五入
问题描述
题目源于计算机二级C语言的程序设计题,做的时候有些懵,虽然说也是做出来了,但是代码写的实在不咋滴。
题目如下:输入一个double类型数据,保留两位,第三位四舍五入,由于题目需要返回值,所以不能直接打印。
1、标准答案
double h = 0.0;
long t = 0, u = 0, v = 0;
double w = 0;
scanf_s("%lf \n", &h);
t = h * 1000;//把第三位小数提到个位上
u = t + 5;//四舍五入,如果大于五就进一位,没进位就不操作
v = u / 10;//截掉第个位(第三位小数)
w = (double)v / 100 ;//将剩余两位原小数位转化回小数
printf("w=%lf \n", w);
最后一步w的值计算,拆开来写会出现没有小数位的情况。
结果:
2、非常好理解的办法(考试这么写的,也没问题,就是时间不大够)
double function()
{
int range = 0, GeWei = 0, ShiWei = 0, BaiWei = 0, QianWei = 0;
//范围、个位、十位、百位、千位
int SF = 0, BF = 0, QF = 0, point1 = 0, point2 = 0, point3 = 0;
//SF:十分位、BF:百分位、WF:千分位
//point1、2、3:小数点后三位
int a[10] = { 0 };
double resultNum = 0.0, h = 0.0;
scanf_s("%lf", &h);
GeWei = (int)h % 10;//堆十取余获得各位
resultNum = h * 0.1;//把十位拉到个位上
ShiWei = (int)resultNum % 10;//获得身处个位的十位值
resultNum = h * 0.01;//把百位拉到个位上
BaiWei = (int)resultNum % 10;//获得身处个位的百位值
resultNum = h * 0.001;//把千位拉到个位上
QianWei = (int)resultNum % 10;//获得身处个位的千位值
resultNum = h * 10;//把十分位扩到个位上
SF = (int)resultNum % 10;//获得身处个位的十分位
resultNum = h * 100;//把十分位扩到个位上
BF = (int)resultNum % 10;//获得身处个位的百分位
resultNum = h * 1000;//把十分位扩到个位上
QF = (int)resultNum % 10;//获得身处个位的千分位
printf("G = %d ", GeWei);
printf("S = %d ", ShiWei);
printf("B = %d ", BaiWei);
printf("Q = %d ", QianWei);
printf("\n");
printf("SF = %d ", SF);
printf("BF = %d ", BF);
printf("QF = %d ", QF);
printf("\n");
a[range] = QianWei;//把他们都写进一个数组里方便后序操作
a[++range] = BaiWei;
a[++range] = ShiWei;
a[++range] = GeWei;
a[++range] = SF;
point1 = range;//三个point记录分位在数组中的下标
a[++range] = BF;
point2 = range;
a[++range] = QF;
point3 = range;
for (int i = 0; i <= range; i++)
{
printf("a[%d] = %d ", i, a[i]);
}
if (a[point3] >= 5)
{
printf("入\n");
a[point2] += 1;
a[point3] = 0;//四舍五入
}
h = QianWei * 1000 + BaiWei * 100 + ShiWei * 10 + GeWei + SF * 0.1 + a[point2] * 0.01;
//按权重求和输出
printf("h = %lf", h);
return h;
}