一个c++程序来计算最大利润

C++ a program to calculate the greatest profit

本文关键字:计算 c++ 程序 一个      更新时间:2023-10-16

该程序接受商品每日价格的输入,然后计算最大利润。价格列表以-1结束。例如,如果我输入20、30、10、50、-1,这意味着第一天商品是20美元,第二天是30美元,以此类推。最大的利润产出将是40美元,因为我可以在第三天以10美元的价格买入,在第四天以50美元的价格卖出。

这是学校的作业,老师不允许我使用数组。现在我的程序很好,除了这个例子。如果我输入20 30 10,最大的利润将是$(30-10),我如何修复它,使它不会存储最大数字之后的数字,例如10作为最小数字?或任何其他代码来实现我的程序的目的?

#include<iostream>
using namespace std;
int main() {
    int c(0), r(0), n1(0), min(0), max(0), l(0), s(0);
    cout << "Please enter the prices: ";
    while (n1 != -1) {
        cin >> n1;
        if (min == 0 && n1>0)
        {
            min = n1;
        }
        c++;
        if (n1 <= 0 && n1 != -1) { cout << "Invalid. Input again. Please make sure it's a positive number!" << endl; r++; }
        else {
            if (n1<min && n1 != -1) { min = n1; s++; }
            if (n1 >= max && (c - r)>(s + 1)) { max = n1; l = c; }
            cout << c << s + 1 << l << endl;
        }
    }
    cout << max << min;
    cout << endl << "Largest amount earned: " << (max - min) << endl;
    return 0;
}

你可以简单地用现在而不是将来的最低价格来计算最大利润。

#include <iostream>
int main(void) {
    int lowestPrice = -1;
    int highestProfit = 0;
    int price, maxProfit;
    while (std::cin >> price) {
        if (price < 0) break;
        if (lowestPrice < 0 || price < lowestPrice) lowestPrice = price;
        maxProfit = price - lowestPrice;
        if (maxProfit > highestProfit) highestProfit = maxProfit;
    }
    std::cout << highestProfit << std::endl;
    return 0;
}