<分区>
最近我一直在学习一些 C++,但我遇到了一个难题:
众所周知,“int”数据类型用于保存整数和整数,而“float”数据类型用于定义保存实数和小数的变量。但是,我发现我可以同样轻松地将整数放入“float”数据类型的变量中,而无需使用“int”类型?
如果是这样,我为什么要继续使用“int”数据类型而不是“float”?使用后者会更方便……它会被认为是不良形式吗?
标签 c++
<分区>
最近我一直在学习一些 C++,但我遇到了一个难题:
众所周知,“int”数据类型用于保存整数和整数,而“float”数据类型用于定义保存实数和小数的变量。但是,我发现我可以同样轻松地将整数放入“float”数据类型的变量中,而无需使用“int”类型?
如果是这样,我为什么要继续使用“int”数据类型而不是“float”?使用后者会更方便……它会被认为是不良形式吗?
最佳答案
它被认为在算术计算中比 int 慢。
由于它们的进动,您可能不会在比较中使用 float 。 (read more here)
这也是一篇好文章:
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/