Howdy_McGee
Howdy_McGee

Reputation: 10673

Type of the quotient of two integers

Consider the following:

int num = 5;
double total = num / 2;

Is it correct to say that the quotient of num / 2 is not a double because you need to parse the int to double?

Upvotes: 1

Views: 926

Answers (1)

Ray Toal
Ray Toal

Reputation: 88428

The technical answer is that the / operator produces an int when given two ints. This computation is done independent of its assignment to a double variable.

You actually do get a double value in the variable total, but it is 2.0, not 2.5. The integer 2 is cast to 2.0 in the initialization.

Your options, if you want 2.5, are:

double total = num / 2.0;

double total = (double)num / 2;

In short, it is not a parsing issue, but rather one of C++ operator semantics. Hope that made sense.

Upvotes: 9

Related Questions