Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ program is rounding by default [duplicate]

Tags:

c++

rounding

I'm currently working on a C++ program where I have a bankAccount class and I need to calculate interest. Problem is, my function is rounding off my numbers to the whole number, even though I'm using a float as my variable type. So if I had code like this:

float BankAccount::CalculateInterest(int Time)
{
    float thing;
    thing = (967 / 365);
    return thing;
}

thing ends up equaling 2.00000000, when it should equal 2.649315068.

Any ideas? I had my interest equation in there before, and the result was always 1.00000000 no matter what, so I put this in as a test and I saw that it's rounding to the "floor".

Thanks for your help!

like image 469
Ben Buurstra Avatar asked Mar 15 '23 03:03

Ben Buurstra


2 Answers

It's not rounding.

You are dividing two integers and the result will be an integer.

You can remedy this by simply adding ".0" to both numbers, or explicitly defining them as floats.

like image 62
It'sPete Avatar answered Mar 16 '23 15:03

It'sPete


967 and 365 are integers, so integer division is used and the remainder discarded. Make one a floating point number and floating point division will be done: 967 / 365.0.

Alternatively:

float thing = 967;  // integer converted to float during assignment
thing /= 365;  // division of float and converted integer
like image 27
Tony Delroy Avatar answered Mar 16 '23 16:03

Tony Delroy