c++c++11type-conversiontypecasting-operator

Division between variable of different types | implicit type casting in C++


Since I am noob in C++, and Udacity Quiz narrates:

The following program produces wrong out put. To fix the program, you need to change at least two of the variable types: the answer, and one of the divisors.

 #include <iostream>
 int main(void)
 {
     int numerator = 4; // no need to change type
     float denominator = 5.0; // changed to float
     float answer = 0.0; // changed to float

     answer = numerator / denominator;
     std::cout<<"answer = "<<answer; // answer = 0.8
     return 0;
 }

Question:How type casting implies here and Why change variable types on both sides of equality.

why not change only answer. as directed I tried setting float to answer and denominator only. and now it works, but I want to learn implicit typecasting in c++.

PS: The code is a quiz by Udacity classroom


Solution

  • If the both operands of the expression

    numerator / denominator
    

    have integer types then the result of the expression is also has the common integer.

    To make the result of a floating type one of the operands has to be of a floating type.

    On the other hand if the variable result has an integer type then there can be a truncation of the floating type expression

    numerator / denominator