c++ - 为什么使用 'int' 数据类型而不是 'float' 数据类型?

标签 c++

<分区>

最近我一直在学习一些 C++,但我遇到了一个难题:

众所周知,“int”数据类型用于保存整数和整数,而“float”数据类型用于定义保存实数和小数的变量。但是,我发现我可以同样轻松地将整数放入“float”数据类型的变量中,而无需使用“int”类型?

如果是这样,我为什么要继续使用“int”数据类型而不是“float”?使用后者会更方便……它会被认为是不良形式吗?

最佳答案

它被认为在算术计算中比 int 慢。
由于它们的进动,您可能不会在比较中使用 float 。 (read more here)

这也是一篇好文章:

Float vs. integer:

Historically, floating-point could be much slower than integer arithmetic. On modern computers, this is no longer really the case (it is somewhat slower on some platforms, but unless you write perfect code and optimize for every cycle, the difference will be swamped by the other inefficiencies in your code).

On somewhat limited processors, like those in high-end cell phones, floating-point may be somewhat slower than integer, but it's generally within an order of magnitude (or better), so long as there is hardware floating-point available. It's worth noting that this gap is closing pretty rapidly as cell phones are called on to run more and more general computing workloads.

On very limited processors (cheap cell phones and your toaster), there is generally no floating-point hardware, so floating-point operations need to be emulated in software. This is slow -- a couple orders of magnitude slower than integer arithmetic.

As I said though, people are expecting their phones and other devices to behave more and more like "real computers", and hardware designers are rapidly beefing up FPUs to meet that demand. Unless you're chasing every last cycle, or you're writing code for very limited CPUs that have little or no floating-point support, the performance distinction doesn't matter to you.

我建议您阅读整篇文章,以清楚地了解它们的区别。

关于c++ - 为什么使用 'int' 数据类型而不是 'float' 数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26227748/

相关文章:

c++ - 这个 char 数组到 std::string 的转换有什么问题?

c++ - 输入到 stringstream 并在单个语句中转换为字符串。没有辅助类可以吗?

c++ - 为什么 std::deque 子数组大小是固定的?

c++ - Qt + CMake + VC++ 生成命令提示符

c++ - 为什么参数中的默认char*必须是const?

c++ - 枚举映射对重构具有鲁棒性

c++ - 使用两个堆栈实现队列 - 出列测试问题?

c++ - 递归地在干草堆中查找针的索引。

c++ - 收到 "vector iterators incompatible"错误

c++ - 传递指针 - 用于写入流