首页 > 解决方案 > 计算现金返还结果为 0

问题描述

我正在创建一个类函数,它返回现金返还现金,它为您提供一个百分比,并且是查看您是否获得良好投资回报率的关键指标。我创建了这个函数,但由于某种原因,它没有给我想要的答案,即“3%”或“50%。现金回报通常是(年现金流/投资现金总额)。它只是返回 0。

double cashOnCashReturn(int cashFlowMonthly, int buyingPrice, double downPaymentP, double closingCost, int repairs) {

    int fullMonth = 12;

    int yearlyCashFlow = cashFlowMonthly * fullMonth;

    double downPaymentPercentage = downPaymentP/100;

    int downPaymentCashInvested = downPaymentPercentage * buyingPrice;

    long closingCostTotal = closingCost * buyingPrice;

    int cashInvestment = downPaymentCashInvested + repairs + closingCostTotal;

    double cashOnCash = (yearlyCashFlow / cashInvestment) * 100;

    cout << fixed << setprecision(0);

    return cashOnCash;
}

我的主要功能如下

int main()
{   
    string address;
    int buyingPrice;
    int rent;
    int cashFlowMonthly;
    int downPayment;
    double closingCostPercent = 0.05;
    int repairCost;

    // Mortgage Calculator Variables
    // double annualInterestRate;
    // double loanAmount;
    // double monthlyInterestRate;
    // double numberOfPayments;
    // double totalPayBack;
    // double monthlyPayment;

    cout << "Address: ";
    getline(cin,address);
    cout << "Buying Price: ";
    cin >> buyingPrice;
    cout << "Down Payment Percentage: ";
    cin >> downPayment;
    std::cout << "Repair Cost: ";
    std::cin >> repairCost;
    cout << "Rent Monthly: ";
    cin >> rent;
    std::cout << "Cashflow Monthly: ";
    std::cin >> cashFlowMonthly;

    realEstate firstHome;
    firstHome.setAddress(address);
    firstHome.setBuyingPrice(buyingPrice);
    firstHome.setRent(rent);
    
    std::cout <<"\n";
    std::cout << "================================================" << std::endl;
    std::cout << "Real Estate Calculator Created By Austin Nguyen" << std::endl;
    std::cout << "================================================" << std::endl;
    std::cout << "Address: " << firstHome.getAddress() << std::endl;
    std::cout << "\n";
    std::cout << "Buying Price: " << firstHome.getBuyingPrice() << std::endl;
    std::cout << "\n";
    std::cout << "Rent: " << firstHome.getRent() << std::endl;
    std::cout << "\n";
    std::cout << "Does It Pass One Percent Rule? " << firstHome.onePercentRule(buyingPrice,rent) << std::endl;
    std::cout << "\n";
    std::cout << "Cash On Cash Return: " << firstHome.cashOnCashReturn(cashFlowMonthly,buyingPrice,downPayment,closingCostPercent,repairCost);
    std::cout << "\n";
    std::cout << "================================================" << std::endl;
    std::cin.clear();

标签: c++c++11

解决方案


yearlyCashFlow并且cashInvestment是整数。将两个整数相除会得到一个整数 - 即使将结果分配给一个双精度数。

aladouble y = 3 / 5导致y分配为零,因为3/5它是一个整数表达式,它被评估为0而不是.6.. 然而3/5.0是一个浮点表达式。

所以这一行:

double cashOnCash = (yearlyCashFlow / cashInvestment) * 100;

真的应该是:

double cashOnCash = (yearlyCashFlow / (double)cashInvestment) * 100;

通过将除法表达式中的一个元素从 int 转换为 double 会导致整个表达式被评估为浮点表达式。


推荐阅读