为什么这回归垃圾?

时间:2016-06-02 12:39:43

标签: c++ 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为&gt; = 27414时,会出现问题。对于小于该值的值,它会给出所需的结果。我无法弄清楚为什么会这样。

非常感谢

1 个答案:

答案 0 :(得分:2)

如果你重写初始化你的变量而不是使用&#34;声明并分配&#34;抗 - &#34;模式&#34; (我也删除了未使用的变量):

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成为唯一缺少初始化的人 它唯一分配值的时间是minCPB >= costPerBattle,因此,如果该条件永远不会让您留下不确定的值。

将其初始化为合情合理的东西。