四舍五入并将其重铸为整数
Rounding off and recast it as integer
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.000000
和 4.000000
。我应该如何将其转换为 int
以获得上述答案 3
和 4
?
您可以声明一个 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
here, and why you should use it instead of C-style casts here。
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.000000
和 4.000000
。我应该如何将其转换为 int
以获得上述答案 3
和 4
?
您可以声明一个 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
here, and why you should use it instead of C-style casts here。