Reputation: 15
My problem is that when dividing two integers I can't get a float value. Here's the code
{
cout << "Kokie skaiciai?" << endl;
cin >> x;
cin >> y;
cout << "Atsakymas: " << dalyba(x, y) << endl;
}
and the function that i use
int dalyba (int x, int y)
{
float z;
z = (float) x / y;
return z;
}
so if x = 5 and y = 2 I get an answer 2 instead of 2.5. Any help would be apreciated.
Upvotes: 1
Views: 258
Reputation: 5972
The return value of your dalyba
function is an int. This should be a float.
float dalyba (int x, int y)
{
float z;
z = (float) x / y;
return z;
}
Upvotes: 5
Reputation: 42934
The problem is that your function returns an int
instead of a float
, so the float result is cast back to an integer, and truncated. You may want to change the return value type of your function from int
to float
.
Moreover, in modern C++, you may want to use C++-style casts like static_cast<>
.
The following snippet prints 2.5
as expected:
#include <iostream>
using namespace std;
float f(int x, int y) {
return static_cast<float>(x) / y;
}
int main() {
cout << f(5, 2) << endl;
}
Upvotes: 1