[英]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;
My task is to round the number first and then cast it to integer: the output of num1 and num2 after round off should be respectively 3.000000
and 4.000000
.我的任务是先将数字四舍五入,然后将其转换为整数:四舍五入后 num1 和 num2 的输出应分别为
3.000000
和4.000000
。 How should I cast it to int
to get the aboved mentioned answers 3
and 4
?我应该如何将它转换为
int
以获得上述答案3
和4
?
You can declare an int
variable and assign the result of the floor
, then output that int
.您可以声明一个
int
变量并分配floor
的结果,然后输出该int
。 The floor is no longer needed either, as the assigning to an int
does that implicitly.也不再需要地板,因为分配给
int
是隐式的。
int i1 = num1+0.5;
cout<<i1<<endl;
Note that in your current code, floor()
does not actually help in any way, as you are discarding the result.请注意,在您当前的代码中,
floor()
实际上没有任何帮助,因为您正在丢弃结果。 floor
is not modifying its parameter, but returning its result, and you are not assigning it to anything. floor
没有修改它的参数,而是返回它的结果,并且你没有将它分配给任何东西。 You could have used, for example,例如,您可以使用
num1 = floor(num1+0.5);
and then num1
would contain the result.然后
num1
将包含结果。
cout<<floor(num1+0.5)<<endl;
will print 3.0
.将打印
3.0
。 You don't need more cast here, but if you want to do it, use static_cast
:你不需要更多的演员在这里,但如果你想这样做,使用
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;
More about static_cast
here , and why you should use it instead of C-style casts here .更多
static_cast
这里,为什么你应该使用它来代替C风格的类型转换这里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.