Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Issue with Type Casting in C++

I’m currently facing an issue while trying to convert a variable from type double to int in C++. When using the static_cast or int() operator for the conversion, the result doesn’t seem to be correct. Can someone guide me on how to properly perform this conversion?

#include <iostream>

int main() {
    double myDouble = 3.14;
    int myInt = static_cast<int>(myDouble); // Also tried int(myDouble)
    std::cout << "Value of myInt: " << myInt << std::endl;

    return 0;
}

Here, the value of ‘myInt’ is always displayed as 3, even if ‘myDouble’ has a fractional value. How can I correctly perform this conversion?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The issue you’re facing is related to the truncation that occurs when converting a double to an int. The fractional part of the double is discarded during this conversion.

If you want to round the double to the nearest integer, you can use the round() function from the <cmath> header. Here’s an updated version of your code:

#include <iostream>
#include <cmath>

int main() {
double myDouble = 3.14;
int myInt = static_cast<int>(std::round(myDouble));
std::cout << "Value of myInt: " << myInt << std::endl;

return 0;
}

Now, std::round() is used to round the double to the nearest integer before the conversion to int takes place. This should give you the desired result.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading