gpt4 book ai didi

C++ 相同的变量充当 int 和 float

转载 作者:行者123 更新时间:2023-11-28 02:08:10 25 4
gpt4 key购买 nike

我遇到的情况是,我需要将值保持为 float 值和整数值。所以像下面这样尝试。但没有帮助。有人可以帮忙吗?

union Val {
int a;
float b;
};

Val p;
p.b = 45.56;

int k = p.a; // i want k should be 45;

最佳答案

我看到了 you say :

i dont want each time it to be converted from float to int [sic]

为此,您可以使用 user-defined conversions来完成这个。

所以你的结构看起来像这样:

class Val {
int a;
float b;
public:
Val& operator= (const int _a) {a = _a; b = _a + fmod(b, 1.0F); return *this;}
Val& operator= (const float _b) {b = _b; a = trunc(_b); return *this;}
operator int() {return a;}
operator float() {return b;}
};

请注意,您真正想要使用的只是一个 float static_cast<int> 对于 static_cast :

No checks are performed during runtime to guarantee that the object being converted is in fact a full object of the destination type. Therefore, it is up to the programmer to ensure that the conversion is safe. On the other side, it does not incur the overhead of the type-safety checks of dynamic_cast.

我提供了使用 Val 的示例这里:http://ideone.com/XUesib但你可以完成完全相同的事情 float foo像这样:

foo = 1.3F;
cout << static_cast<int>(foo) << endl << foo << endl;
foo = 13 + fmod(foo, 1.0F);
cout << static_cast<int>(foo) << endl << foo << endl;

关于C++ 相同的变量充当 int 和 float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36717725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com