简体   繁体   English

在 C++ 中将 float 转换为 int

[英]Casting float to int in C++

int uniquePaths(int m, int n) {
    int num = m+n-2;
    int den=1;
    double ans = 1;
    while(den<=m-1) {
        ans = ans*(num--)/(den++);
    }
    cout<<ans;
    return (int)ans; 
}

The expected answer for m=53, n=4 as input to the above piece of code is 26235 but the code returns 26234. However, the stdout shows 26235.作为上述代码段输入的 m=53、n=4 的预期答案是 26235,但代码返回 26234。但是,stdout 显示 26235。

Could you please help me understand this behavior?你能帮我理解这种行为吗?

Due to floating-point rounding, your code computes ans to be 26,234.999999999985448084771633148193359375.由于浮点舍入,您的代码计算出ans为 26,234.999999999985448084771633148193359375。 When it is printed with cout<<ans , the default formatting does not show the full value and rounds it to “26235”.当使用cout<<ans打印时,默认格式不显示完整值并将其四舍五入为“26235”。 However, when the actual value is converted to int , the result is 26,234.但是,当实际值转换为int时,结果为 26,234。

After setting num to m+n-2 , your code is computing num !num设置为m+n-2后,您的代码正在计算num / (( m-1 )!( num-m+1 ),), which of course equals num ! / (( m-1 )!( num-m+1 ),), 当然等于num / (( num-m+1 )!( m-1 ).), Thus, you can use either m-1 or num-m+1 as the limit. / (( num-m+1 )!( m-1 ).),因此,您可以使用m-1num-m+1作为极限。 So you can change the while line to these two lines:因此,您可以将while行更改为这两行:

    int limit = m-1 < num-m+1 ? m-1 : num-m+1;
    while(den<=limit) {

and then your code will run to the lower limit, which will avoid dividing ans by factors that are not yet in it.然后你的代码将运行到下限,这将避免将ans除以尚未包含的因素。 All results will be exact integer results, with no rounding errors, unless you try to calculate a result that exceeds the range of your double format where it is able to represent all integers (up to 2 53 in the ubiquitous IEEE-754 binary64 format used for double ).所有结果都将是精确的 integer 结果,没有舍入错误,除非您尝试计算的结果超出double精度格式的范围,在该范围内它能够表示所有整数(在使用的无处不在的 IEEE-754 binary64 格式中最多为 2 53对于double )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM