C在数学计算中将double转换为int

前端之家收集整理的这篇文章主要介绍了C在数学计算中将double转换为int前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我写cout<< 3.0 / 2.0;
我得到1.5
但是当我写cout<< 3.0 * 2.0;
我得到6.
如果3.0和2.0是双值,我的结果不应该像6.0这样的双倍值吗?
根据int或double的结果是什么?

解决方法

3.0 * 2.0的结果非常多(a).但是,值的表示不是值.您会发现6,6.0,6.000000,0.06E2,6000E-3甚至符号-6(epi×i)都是相同的值,具有不同的表示.

如果您不想使用默认演示文稿(b),iostream和iomanip标头可以设置格式化特定格式的数字,例如使用它来获取6.0:

#include <iostream>
#include <iomanip>
int main() {
    auto x = 3.0 * 2.0;
    std::cout << std::setprecision(1) << std::fixed << x << '\n';
}

(a)标准中规定的通常算术转换在这里发挥作用(例如,C 17 8表达式/ 11):

Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type,which is also the type of the result. This pattern is called the usual arithmetic conversions,which are defined as follows:

  • If either operand is of scoped enumeration type,no conversions are performed; if the other operand does not have the same type,the expression is ill-formed.
  • If either operand is of type long double,the other shall be converted to long double.
  • Otherwise,if either operand is double,the other shall be converted to double.
  • Other irrelevant stuff in the context of this question.

(b)默认情况下打印的内容的实际规则在标准中指定,但复杂且区域设置足够大,以至于大多数人可能更容易进行显式格式化:-)

原文链接:https://www.f2er.com/c/116023.html

猜你在找的C&C++相关文章