作为一名测绘专业的学生,在内业计算中经常遇到遇到小数点后保留几位小数的问题。根据《工程测量实验教程》(王宇会 著)一书,内业计算按“四舍六入,五前单进双舍(或称奇进偶不进)”的取舍规则进行尾数的取舍。如数据1.1235和1.1245小数点后保留三位时,均应为1.124
//四舍六入五成双的基于C++11的实现
//C++11中sprintf、strncpy由于VS2015会报错,所以在这里改用sprintf_s、strncpy_s
#include #include #include using namespace std;
const int n = 1000; //设置要保留的位数
char s1[20];
char s2[20];
int main()
{
double a1, a2, a3;
cin >> a1;
a2 = a1*n; //将输入的数据乘以n,使得小数点后的第一位使我们要判断的是否为5的数
sprintf_s(s1, "%lf", a2); //将double类型的a2打印到字符数组s1里面去
int b = strcspn(s1, "."); //整型b即为小数点在字符数组中序号
char c = s1[b + 1]; //字符c即为小数点后一位数
if (c'5') //如果c大于5,则进1
{
strncpy_s(s2, s1, b);
a3 = atof(s2) + 1;
}
else
{