简体   繁体   中英

Converting int to double in C++

I can not get a simple conversion from int to double to work

#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.

AFAIK, d1 and d2 should be 8.0 , shouldn't then?

Can anyone, please, tell me what am I doing wrong?

I am setting g++ compiler, verion 7.4.0, conformance to C++11.

Thanks!

I can not get a simple conversion from int to double to work

Actually, the conversion itself works just fine.

d1 and d2 equals 8, instead of 8.0

8 and 8.0 are two ways of representing the same value as a string. There is no difference in the value.

AFAIK, d1 and d2 should be 8.0, shouldn't then?

They are, because 8 and 8.0 are the same exact value.

Can anyone, please, tell me what am I doing wrong?

Your mistake is expecting the output to be 8.0. The correct output is 8, because of the default formatting settings of the output stream.

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.

If your intention was to output 8.0, then your mistake was to not use the correct stream manipulators to achieve that format. In particular, you need to use the std::fixed manipulator to show fixed number of decimals, even when they are zero. You can use std::setprecision to set the number of decimals to show. Depending on how you want the output formatted in different cases, std::showpoint might also be an option.

Make no mistake, d1 and d2 are double s. You need std::setprecision() (and apparently std::fixed ) too found in the header <iomanip> :

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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