Home > Blockchain >  not getting same output via user defined function
not getting same output via user defined function

Time:10-20

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?

CodePudding user response:

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
}

CodePudding user response:

The expression

x / y

or

a / b

has the type float. And in the statement below the value of the expression without any truncation is assigned to the float variable c.

c = a / b;

On the other hand, the returned value of this call

sum(12, 5)

is converted to the type int due to the return type of the function. So the returned value can be truncated.

To get the expected result change the return type of the function to the type float

float sum(int x, float y){
    return (x / y);
}
  • Related