说明
四舍五入的函数参数可以有多种数据类型。不同的数据类型有不同的结果。
当他的参数应该是浮点数的时候,结果才是真正的四舍五入。
例子
/*
g++ -g -std=c++17 ./src/basic_demo.cpp -o basic_demo
*/
#include <iostream>
#include <cmath>
void test_round(){
// 参数是浮点数的情况,结果正确
std::cout << "std::round(12.369)\t" << std::round(12.369) << std::endl;
std::cout << "std::round(12.9)\t" << std::round(12.9) << std::endl;
int a1 = 10;
int a2=13;
int b=7;
//参数是整数组成的分子和分母的时候,结果错误
std::cout << "std::round(10/7)\t" << std::round(10/7) << std::endl;
std::cout << "std::round(13/7)\t" << std::round(13/7) << std::endl;
//调整一下参数的类型,结果正确
std::cout << "std::round(1.0*10/7)\t" << std::round((1.0*10)/7) << std::endl;
std::cout << "std::round(1.0*13/7)\t" << std::round((1.0*13)/7) << std::endl;
}
int main(int argc, char **argv)
{
test_round();
return 0;
}
程序的结果
baby@ubuntu2204:~/devel/cpp$ ./basic_demo
std::round(12.369) 12
std::round(12.9) 13
std::round(10/7) 1
std::round(13/7) 1
std::round(1.0*10/7) 1
std::round(1.0*13/7) 2
网友评论