Skip to content

Instantly share code, notes, and snippets.

@mshafae
Created October 3, 2023 04:46
Show Gist options
  • Save mshafae/7b281ca822da831d8ffb85982034c917 to your computer and use it in GitHub Desktop.
Save mshafae/7b281ca822da831d8ffb85982034c917 to your computer and use it in GitHub Desktop.
CPSC 120 Example of using trunc to truncate a double and static_cast to convert a double to an int.
// cpsc120_trunc_convert_double.cc
// Gist https://gist.github.com/mshafae/7b281ca822da831d8ffb85982034c917
#include <cmath>
#include <iostream>
#include <limits>
int main(int argc, char const *argv[]) {
// This is a really large number, a 1 with 308 zeros after it.
// double decimal_number{1.0e308};
// This is a relatively small number.
double decimal_number{123.456};
double integer_part{NAN};
int converted_and_truncated{0};
// Is decimal_number safe to truncate and convert to an integer? Check to see
// if it is less than the largest int and greater than the smallest int.
if (decimal_number < std::numeric_limits<int>::max() &&
decimal_number > std::numeric_limits<int>::min()) {
integer_part = trunc(decimal_number);
converted_and_truncated = static_cast<int>(integer_part);
std::cout << "Converted " << decimal_number << " to "
<< converted_and_truncated << "\n";
} else {
std::cout << "Cannot convert " << decimal_number << " to an int.\n";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment