Search code examples
c++return-valueimplicit-conversionreturn-type

not getting same output via user defined function


I was trying something in Cpp, but not getting same output when I used the same thing in a user defined function
CODE

#include <iostream>
using namespace std;
int sum(int x, float y){
    return (x / y);
}
int main(){
    int a;
    float b, c;
    a = 12;
    b = 5;
    c = a / b;
    cout << sum(12, 5) << endl;
    cout << c;
}

OUTPUT

2
2.4

Why am I not getting 2.4 in both the cases?


Solution

  • The return value of sum is int.

    #include <iostream>
    using namespace std;
    int sum(int x, float y){ 
        return (x / y);                                //<< this is an int
    }
    int main(){
        int a;
        float b, c;
        a = 12;
        b = 5;
        c = a / b; << this is a float
        cout << sum(12, 5) << endl;                   //<< prints an int
        cout << c;                                    //<< prints a float
    }