如何用两个int相除得到一个double数呢,c++
时间: 2024-10-23 16:05:58 浏览: 33
double类型精度丢失;double转换到64位整数
在C++中,如果你想要用两个整数相除并得到一个double类型的商,你可以将其中一个操作数转换为double类型。这里有一个简单的示例[^1]:
```cpp
int numerator = 10;
int denominator = 3;
double result = static_cast<double>(numerator) / denominator;
std::cout << "The division of " << numerator << " by " << denominator << " as a double is: " << result << std::endl; // 输出:The division of 10 by 3 as a double is: 3.33333
```
通过`static_cast<double>()`,我们把整数`numerator`转换为double类型,然后再进行除法运算。
如果你想保持小数部分,即使它小于1,也可以这样做:
```cpp
int numerator = 10;
int denominator = 3;
double result = (double)numerator / denominator;
std::cout << "The division of " << numerator << " by " << denominator << " with no truncation is: " << result << std::endl; // 输出:The division of 10 by 3 with no truncation is: 3.33333
```
在这个例子中,`(double)`同样实现了从int到double的转换,但没有`static_cast`那样明确的类型转换语法。
阅读全文