四舍五入并将其重新转换为整数

Rounding off and recast it as integer

本文关键字:转换 整数 新转换 四舍五入      更新时间:2023-10-16
double num1=3.3;
double num2=3.8;
//print output and round off
cout<<floor(num1+0.5)<<endl;
cout<<floor(num2+0.5)<<endl;

我的任务是先将数字四舍五入,然后将其转换为整数:num1和num2四舍五入后的输出应该分别是3.0000004.000000。我应该如何将其转换为int以获得上述答案34 ?

您可以声明一个int变量并分配floor的结果,然后输出int。floor也不再需要了,因为对int的赋值隐式地完成了这个操作。

int i1 = num1+0.5;
cout<<i1<<endl;

请注意,在您当前的代码中,floor()实际上没有任何帮助,因为您正在丢弃结果。floor没有修改它的参数,而是返回它的结果,并且您没有将它赋值给任何东西。例如,你可以使用
num1 = floor(num1+0.5);
然后num1将包含结果

cout<<floor(num1+0.5)<<endl;将打印3.0。这里不需要更多的强制转换,但如果你想这样做,使用static_cast:

double num1=3.3;
double num2=3.8;
// to round off
int num1_as_int = static_cast<int>(floor(num1+0.5));
int num2_as_int = static_cast<int>(floor(num2+0.5));
//print output
cout<<num1_as_int<<endl;
cout<<num2_as_int<<endl;
关于static_cast的更多信息,以及为什么你应该使用它而不是c风格的强制转换。