带浮点变量的 C++ 递归函数

标签 c++ floating-point

考虑以下代码:

#include <iostream>
using namespace std;
int rec(float in){
   if(in < 0) return 0;
   else if(n == 0) return 1;
   else return(rec(in-.2));
}
int man(){
   int n;
   cin >> n;
   cout << rec (n);
   return 0;
}

我希望它在输入为 1 时打印 1。但它打印了 0。这里出了什么问题?

最佳答案

在这些行中

if(in < 0) return 0;
else if(in == 0) return 1;

您的代码正在对整数和 float 进行比较。特别是“in < 0”和“in == 0”。这通常不会给您预期的结果 for various reasons (see article) .

现在,您可以将值 0 转换为 float ,或将其更改为“0.0”,但这并不能真正解决您的问题。

真正的问题是,每次您从数字中减去 0.2,它创建的数字几乎比以前少但不完全是 0.2。发生这种情况是因为在 c/c++ 中, float 使用称为 IEEE Standard for Floating-Point Arithmetic / IEEE 754 的标准格式以二进制形式表示/存储。 .根据我之前链接的文章,它可能不会将中间结果存储为 0.8 -> 0.6 -> 0.4 等。

您可以通过回显 rec: 中的值来快速检查实际发生的情况:

#include <limits>
// allows for use of numeric_limits<float>::digits10
// which tells us the precision of 
// the floating point number represented in decimal
// without having to know the specifics of the platform.

/*** [omitted code] ***/

int rec(float in){
   cout << setprecision(numeric_limits<float>::digits10) << in << ' ' << flush;
   /* flush will force the ostream to display to the screen
      instead of waiting for the buffer to fill up.
      useful if the recursive function never exits for some reason. */
   if(in < 0) return 0;
   else if(in == 0) return 1;
   else return(rec(in-.2));
}

而且您应该看到“in”的值实际上从未真正等于 0,因此返回 1 的代码位实际上从未被触发。

实际值会因您的 CPU 体系结构而异 - 我很想看看您的输出结果。

关于带浮点变量的 C++ 递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33843717/

相关文章:

c++ - DbgHelp - 获取完整的符号签名(函数名称+参数类型)

c++ - 为给定窗口遍历 MSAA 树的代码(Microsoft Active Accessibility)?在 C/C++ 中

python - 无法将数组转换为 float python

c++ - 通过文本文件往返的 float 校验和

go - 是否有任何标准库可以将 float64 转换为具有固定宽度和最大有效位数的字符串?

c++ - 对于 OpenCV/C++,无法将 Mat 写入 JPG 或 BMP 以外的任何其他图像格式

c++ - 如何在不使用 CRT 的情况下将 double 转换为字符串

c++ - GCC __attribute__ 在 32 字节处对齐的 AVX 向量化代码中的段错误

swift - 为什么 Int(Float(Int.max)) 给我一个错误?

c++ - 奇怪的汇编程序...这可能是我的应用程序崩溃的原因吗?