为什么这是返回垃圾?

Why is this returning Garbage?

我正在为游戏制作计算器。
我通常首先确保代码在 C++ 中工作,然后将其转换为所需的语言。我制作了这个程序。在此程序中,有时 optDura 存储正确的值,有时存储垃圾。

这是代码:-

#include <iostream>
using namespace std;

/* 
    cd - current Durability
    se - smith efficiency in decimal
    sc - smith charges in decimal
    sE - smith efficiency in %
    sC - smith charges in %
    ic - initial cost
    md - maximum durability
    tmd - temporary maximum durability
    tD - temporary durability
    td - total durability
    rc - repair cost
    cpb - cost per battle
*/
int main(){

    long int currDura, maxDura, tempMaxDura, tempDura, totDura, optDura;
    double iniCost, repCost;
    long int  smithEffi, smithCharge;
    double se, sc;
    double totCostTillNow, costPerBattle = 0, minCPB;
    int i;
    long int repCount = 1;
    iniCost = 25500;
    currDura = 58;
    maxDura = 59;
    repCost = 27414;
    se = 0.90;
    sc = 0.85;
    tempMaxDura = maxDura;
    tempDura = currDura;
    totDura = tempDura;
    totCostTillNow = iniCost;
    costPerBattle = totCostTillNow / totDura;
    minCPB = costPerBattle;
    cout<<"\n Cost without any repair = "<<costPerBattle;

    for(i=1; i<=maxDura; i++)
    {
        totCostTillNow += (double) repCost * sc;
        tempDura = tempMaxDura * se;
        totDura += tempDura;
        costPerBattle = (double) (totCostTillNow / totDura);
        tempMaxDura -= 1;
        if ( minCPB >=  costPerBattle )
        {
            minCPB = costPerBattle;
            optDura = tempMaxDura;
        }
    }
    cout<<"\n Minimum cost per battle = "<<minCPB<<" & sell at 0/"<<optDura;
    return 0;
}

当 repCost >= 27414 时会出现问题。对于小于该值的值,它会给出所需的结果。我无法弄清楚为什么会这样。

非常感谢

如果您重写以初始化您的变量而不是使用 "declare and assign" 反 "pattern"(我还删除了未使用的变量):

int main(){  
    long int currDura = 58;
    long int maxDura = 59;
    long int tempMaxDura = maxDura;
    long int tempDura = currDura;
    long int totDura = tempDura;
    long int optDura; 
    double iniCost = 25500;
    double repCost = 27414;
    double se = 0.90;
    double sc = 0.85;
    double totCostTillNow = iniCost;
    double costPerBattle = totCostTillNow / totDura;
    double minCPB = costPerBattle;

    cout<<"\n Cost without any repair = "<<costPerBattle;

    for(int i=1; i<=maxDura; i++)
    {
        totCostTillNow += repCost * sc;
        tempDura = tempMaxDura * se;
        totDura += tempDura;
        costPerBattle = totCostTillNow / totDura;
        tempMaxDura -= 1;
        if ( minCPB >=  costPerBattle )
        {
            minCPB = costPerBattle;
            optDura = tempMaxDura;
        }
    }
    cout<<"\n Minimum cost per battle = "<<minCPB<<" & sell at 0/"<<optDura;
    return 0;
}

然后 optDura 是唯一缺少初始化的。
它被赋值的唯一一次是 if minCPB >= costPerBattle,因此如果该条件永远不成立,您将得到一个不确定的值。

将其初始化为合理的值。