优化计算利润最大化公寓租赁数量的计划

时间:2017-03-21 03:08:36

标签: c++ do-while

对于我的C ++课程,其中一个编程练习是构建一个程序,在给定某些变量的情况下,返回利润最大化的公寓租赁数量。我的代码有效,除了答案是低于正确答案的答案。这是我的代码:

   // ch5ProgExercise28.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>

using namespace std;

int main()
{
    int totalUnits, occupiedUnits, vacantUnits;
    double rentAllOccupied, rentIncreaseVacant, maintenance, oldProfit, newProfit;

    cout << "Enter the total number of units, the rent to occupy all the units,"
        << " the increase in rent that results in a vacant unit, and the amount"
        << " to maintain a rented unit.";
    cin >> totalUnits >> rentAllOccupied >> rentIncreaseVacant >> maintenance;
    oldProfit = ((rentAllOccupied)*totalUnits) - (maintenance*totalUnits);
    occupiedUnits = totalUnits;
    vacantUnits = totalUnits - occupiedUnits;
    do
    {
        oldProfit = (rentAllOccupied + (rentIncreaseVacant*vacantUnits))*
            occupiedUnits - (maintenance*occupiedUnits);
        occupiedUnits--;
        vacantUnits = totalUnits - occupiedUnits;
        newProfit = (rentAllOccupied + (rentIncreaseVacant*vacantUnits))*
            occupiedUnits - (maintenance*occupiedUnits);
    } while (oldProfit < newProfit);
    occupiedUnits += 1;
    cout << "To maximize profits, " << occupiedUnits << " units will be rented." << endl;
    cin >> oldProfit; //stops the program from exiting right away
    return 0;
}

是否有更好的循环结构我可以使用,以使被占用的单位数正确而无需为其添加1以获得正确的答案?感谢。

1 个答案:

答案 0 :(得分:0)

您遇到的问题是您的循环条件依赖于newProfit而newProfit计算需要占用单位 - 1.您需要更改循环条件或计算newProfit以获得所需内容。一种方法是循环遍历所有的unusedUnits值,并将最大利润和单位存储在新变量中。你没有提供任何测试条件,但这样的事情应该有效:

double maxProfit = 0;
int maxUnits = 0;

while(occupiedUnits > 0)
{
    oldProfit = (rentAllOccupied + (rentIncreaseVacant*vacantUnits))*
        occupiedUnits - (maintenance*occupiedUnits);
    occupiedUnits--;
    vacantUnits = totalUnits - occupiedUnits;
    newProfit = (rentAllOccupied + (rentIncreaseVacant*vacantUnits))*
        occupiedUnits - (maintenance*occupiedUnits);

    if (newProfit > maxProfit)
    {
        maxProfit = newProfit;
        maxUnits = occupiedUnits + 1;
    }
}
cout << "To maximize profits, " << maxUnits << " units will be rented." << endl;