educative.io

Quiz: Primitive or Fundamental Data Types

why the correct answer is 18 ?, if it always truncate when use (int), why 18.9 don’t truncate into 19 ?


Course: https://www.educative.io/courses/cpp-basics
Lesson: https://www.educative.io/courses/cpp-basics/N01GWKQ0Ql8

Hi @Sean_Chrollo !!
In C++, when we initialize an int variable with a decimal value (like 18.9), the fractional part is truncated, not rounded. Truncation means that everything after the decimal point is simply discarded, and the integer part is kept.

In the example,

int main() 
{  
int number = 18.9;  
cout << "Number = " << number << endl;
}

the variable number is of type int, so the fractional part of 18.9 (which is 0.9) is discarded, and the value stored in the variable becomes 18.

If you want the value to be rounded to the nearest integer, you can use the round() function from the <cmath> library. Here’s how you could modify your code to get the result you expect:

#include <iostream>
#include <cmath>

int main() {
  int number = std::round(18.9);
  std::cout << "Number = " << number << std::endl;
}

With this change, the output will be:

Number = 19

The round() function correctly rounds the value 18.9 to the nearest integer, which is 19.
I hope it helps. Happy Learning :blush: