You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++技术问询:double整数值转int及int用3.赋值是否合法

Hey there! Let's break down your two C++ questions clearly and simply.

问题1:如何将double类型中的整数值转换为int类型数据?

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!

问题2:int类型可以用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—so int i = 3.9; would set i to 3.
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:18:00