C++ getting integer instead of a float value -
my problem when dividing 2 integers can't float value. here's code
{ cout << "kokie skaiciai?" << endl; cin >> x; cin >> y; cout << "atsakymas: " << dalyba(x, y) << endl; }
and function use
int dalyba (int x, int y) { float z; z = (float) x / y; return z; }
so if x = 5 , y = 2 answer 2 instead of 2.5. apreciated.
the problem function returns int
instead of float
, float result cast integer, , truncated. may want change return value type of function int
float
.
moreover, in modern c++, may want use c++-style casts static_cast<>
.
the following snippet prints 2.5
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; }
Comments
Post a Comment