C++技术问询:double整数值转int及int用3.赋值是否合法
Hey there! Let's break down your two C++ questions clearly and simply.
If you've got a double that holds an exact integer value (like 3.0, 10.0), there are a couple of reliable ways to convert it to an int in C++:
- Static Cast (C++-Style, Recommended): Use
static_cast<int>(your_double_var)—this is the type-safe, explicit way to handle the conversion. It makes your intent clear to both the compiler and other developers. Example:double num = 15.0; int converted_num = static_cast<int>(num); // converted_num will be 15 - C-Style Cast: You can also use
(int)your_double_var, which works but is less explicit and not as type-safe as static_cast. It's a holdover from C, so it's better to stick with static_cast in modern C++. Example:double num = 8.0; int converted_num = (int)num; // converted_num will be 8
A quick note: If your double isn't an exact integer (like 4.9), both methods will truncate the decimal part (so 4.9 becomes 4). Also, if the double value is outside the range of what an int can hold, the result is undefined behavior—always make sure your value fits within the int's limits!
3.这样的浮点数赋值吗? Great question! Let's start with your example code:
#include <iostream> using namespace std; int main(){ int i = 3.; }
Yes, this is valid C++ code! The compiler will automatically perform an implicit conversion from the double literal 3. (which is identical to 3.0) to an int. The end result is that i will hold the value 3, just like if you wrote int i = 3;.
That said, keep these points in mind:
- If you use a non-integer double literal (like
3.9), the compiler will still convert it to int, but it will truncate the decimal part—soint i = 3.9;would setito3. - Some compilers might issue a precision loss warning when assigning a double to an int, especially if the value isn't an exact integer. This is just the compiler reminding you that you could lose data in the conversion.
内容的提问来源于stack exchange,提问作者Klaus By

