C++程序默认四舍五入

C++ program is rounding by default

我目前正在开发一个 C++ 程序,我有一个 bankAccount class,我需要计算利息。问题是,我的函数将我的数字四舍五入为整数,即使我使用浮点数作为我的变量类型。所以如果我有这样的代码:

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

当它应该等于 2.649315068 时,它最终等于 2.00000000。

有什么想法吗?我之前有我的兴趣方程,结果总是 1.00000000 无论如何,所以我把它作为测试,我看到它四舍五入到 "floor".

感谢您的帮助!

967365 是整数,因此使用整数除法并舍弃余数。使一个浮点数和浮点除法将完成:967 / 365.0.

或者:

float thing = 967;  // integer converted to float during assignment
thing /= 365;  // division of float and converted integer

不是四舍五入。

您将两个整数相除,结果将是一个整数。

您可以通过简单地向两个数字添加“.0”或将它们明确定义为浮点数来解决这个问题。