简体   繁体   English

在 C++ 中将 int 转换为 double

[英]Converting int to double in C++

I can not get a simple conversion from int to double to work我无法从intdouble进行简单的转换才能工作

#include <iostream>

int main()
{
  int i = 8;
  double d1 = i;
  double d2 = static_cast<double>(i);
  std::cout << "i = " << i << ", d1 = " << d1 << ", d2 = " << d2 << std::endl;
  return 0;
}

d1 and d2 equals 8 , instead of 8.0 , not only in stdout , but also in the debugger of QtCreator. d1d2等于8 ,而不是8.0 ,不仅在stdout ,而且在 QtCreator 的调试器中。

AFAIK, d1 and d2 should be 8.0 , shouldn't then? AFAIK, d1d2应该是8.0 ,不是吗?

Can anyone, please, tell me what am I doing wrong?谁能告诉我我做错了什么?

I am setting g++ compiler, verion 7.4.0, conformance to C++11.我正在设置 g++ 编译器,版本 7.4.0,符合 C++11。

Thanks!谢谢!

I can not get a simple conversion from int to double to work我无法从 int 到 double 进行简单的转换才能工作

Actually, the conversion itself works just fine.实际上,转换本身工作得很好。

d1 and d2 equals 8, instead of 8.0 d1 和 d2 等于 8,而不是 8.0

8 and 8.0 are two ways of representing the same value as a string. 8 和 8.0 是将相同值表示为字符串的两种方式。 There is no difference in the value.值没有区别。

AFAIK, d1 and d2 should be 8.0, shouldn't then? AFAIK,d1 和 d2 应该是 8.0,不是吗?

They are, because 8 and 8.0 are the same exact value.它们是,因为 8 和 8.0 是相同的精确值。

Can anyone, please, tell me what am I doing wrong?谁能告诉我我做错了什么?

Your mistake is expecting the output to be 8.0.您的错误是期望输出为 8.0。 The correct output is 8, because of the default formatting settings of the output stream.由于输出流的默认格式设置,正确的输出是 8。

Another mistake is assuming that there is a problem with the conversion from int to double, when the problem is actually in the formatting of the textual output.另一个错误是假设从 int 到 double 的转换有问题,而实际上问题出在文本输出的格式上。

If your intention was to output 8.0, then your mistake was to not use the correct stream manipulators to achieve that format.如果您的意图是输出 8.0,那么您的错误就是没有使用正确的流操作器来实现该格式。 In particular, you need to use the std::fixed manipulator to show fixed number of decimals, even when they are zero.特别是,您需要使用std::fixed操纵器来显示固定的小数位数,即使它们为零。 You can use std::setprecision to set the number of decimals to show.您可以使用std::setprecision设置要显示的小数位数。 Depending on how you want the output formatted in different cases, std::showpoint might also be an option.根据您希望在不同情况下格式化输出的方式, std::showpoint也可能是一个选项。

Make no mistake, d1 and d2 are double s.毫无疑问, d1d2double s。 You need std::setprecision() (and apparently std::fixed ) too found in the header <iomanip> :您也需要在标题<iomanip>找到std::setprecision() (显然还有std::fixed ):

#include <iostream>
#include <iomanip>

int main()
{
  int i = 8;
  double d1 = i;
  double d2 = static_cast<double>(i);
  std::cout << "i = " << i << std::fixed << std::setprecision(2) << ", d1 = " << d1 << ", d2 = " << d2 << std::endl;
  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM