C++ 将 int 转换为 double

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19977565/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:18:23  来源:igfitidea点击:

C++ casting int to double

c++casting

提问by nenito

I'm not a C++ developer, but today I've found a C++ code and try to understand it. So I've stacked on this piece of code:

我不是 C++ 开发人员,但今天我找到了 C++ 代码并尝试理解它。所以我堆积了这段代码:

int m = 2, n = 3, i = 1;
double mid = (double)m / n * i;
int d = (int)mid + 1;

printf("%d %d\n", mid, d);

The result which is going to be printed to the console is: 1431655765 1071994197. It seems to be related with the casting of variable m to double, but I have no idea how it is happening. I need someone to help me understand it. Thanks in advance!

将要打印到控制台的结果是:1431655765 1071994197。这似乎与将变量 m 强制转换为双倍有关,但我不知道它是如何发生的。我需要有人帮助我理解它。提前致谢!

回答by Ivaylo Strandjev

You should print a double(mid) with the %lfformat specifier in printf.

您应该打印双(mid)与%lf格式符printf

回答by PoP

Changing the printf to

将 printf 更改为

printf("%f %i\n", mid, d);

will actually print what you expect i.e., 0.666667 1

实际上会打印您期望的内容,即 0.666667 1

回答by Emeche Cash

A simpler way to solve it would be

一种更简单的解决方法是

double m_Doubled;
m_Doubled = static_cast(m);