-1

So I want to print an integer as a double, so I used type casting. I do not want to change the type of the result variable, because I also want to assign to it integer arithmetic operations. Here is my code:

int result {0};

result = 40 / 60;
cout << "Result casted to a double " << (double)result << endl;//output: 0

Did I do something wrong here? Did I correctly cast the result to a double because here it seems that it does not work. Thanks in advance.

Alex
  • 840
  • 7
  • 23
  • 4
    40/60 is 0 in integer arithmetic. Integers truncate the result of a division to the whole number. You need to change result to be of type `double` for this to work. – nick Mar 06 '20 at 11:27

2 Answers2

1

The important thing is at least one element of calculation be a float-double. To get a double result you need to cast one of them as shown below:

    int result = 40;
    cout << "Result casted to a double " << (static_cast<double>(result)/60) << endl;

Or you can create it directly as a float-double.

    double result2 = 40.0 / 60;
    cout << "Result casted to a double " << result2 << endl;

Note that one of elements must have the '.0' to indicate a division of a float-double type by an integer in the case above. Otherwise, despite the result2 be a double, the result will be zero too.

TheArchitect
  • 1,160
  • 4
  • 15
  • 26
0

The problem is not the point of the output, but the point of the calculation:

int result {0};
result = 40 / 60;

This performs an integer division of 40/60 which results in the integer value 0.

The cast in the output now simply casts your integer 0 to a double 0.0

To get the exact result, you need to perform the computation in double and save the result as double:

double result = 40.0 / 60.0;

An alternative approach is to store the result in a user-defined rational number type that keeps both the dividend and the divider as separate integers. That way you don't need to pass the result in double form around and only switch to double for printing. But you have to perform the division of doubles at some point to get the desired output.

ComicSansMS
  • 51,484
  • 14
  • 155
  • 166
  • 1
    Hello, thank you for your response however is this possible without having to change the type of result? – Alex Mar 06 '20 at 11:31
  • @Alex Unfortunately not, as integer division throws away the remainder: 40 divided by 60 is 0, remainder 40. The remainder part is lost when using the `/` operator on integers. Unless you retain that information manually in another variable, you won't be able to retrieve it from the result. – ComicSansMS Mar 06 '20 at 11:35