我的程序永远循环并且只做了我告诉它做的一半

My program loops forever and does only a half of what I told it to do

我是编程新手,我开始制作自己的 Fire Emblem 升级计算器,但由于某种原因它会无限循环。我找不到答案。 你能在我的代码中查找任何错误吗?

#include<iostream>
#include<cstdlib>
#include<windows.h>
int main () {
using std::cout;
using std::cin;
using std::endl;
int level ,str , skl, lck, def, res, inc, hp, spd, nr ;
char cha[10];
nr=1;
cout<< "Which character?";
cin>> cha ;
cout<< "You chose" << cha << "." << endl << "What level do you want him/her to be?";
cin>> level ;
        if (cha[6] = 'Dieck' ) {
            hp = 26;
            str = 9;
            skl = 12;
            spd = 10;
            lck = 4;
            def = 6;
            res = 1;
            while (level > 0) {

            if (rand() % 100 < 90) {
                inc=1;
                //cout<< "HP increased by" << inc ;
                hp+1;

        }
            if (rand() % 100 < 40) {
                inc=1;
            //  cout<< "Strenght/Magic increased by" << inc ;
                str+1;  
        }
            if (rand() % 100 < 40) {
                inc=1;
                //cout<< "Skill increased by" << inc ;
                skl+1;  
        }
            if (rand() % 100 < 30) {
                inc=1;
            //  cout<< "Speed increased by" << inc ;
                spd+1;  
        }
            if (rand() % 100 < 35) {
                inc=1;
                //cout<< "Luck increased by" << inc ;
                lck+1;  
        }
            if (rand() % 100 < 20) {
                inc=1;
                //cout<< "Defense increased by" << inc ;
                def+1;  
        }
            if (rand() % 100 < 15) {
                inc=1;
                //cout<< "Resistance increased by" << inc ;
                res+1;

        }
        nr+1;
        level-1;
        //cout<<"NR."<< nr << " New stats (in order) HP/STR/SKL/SPD/LCK/DEF/RES " << hp <<" "<< str <<" "<< skl <<" "<< spd <<" "<< lck <<" "<< def <<" "<< res << endl; 
        Sleep(1);

        }
        cout<< "Stats "<< "HP/STR/SKL/SPD/LCK/DEF/RES " << hp <<" "<< str <<" "<< skl <<" "<< spd <<" "<< lck <<" "<< def <<" "<< res << endl;
        return 0 ;
}

}

您遇到的一个问题是 cha[6] = 'Dieck'

cha[6] 是单个字符,例如 'D' 或 'i' 但不是整个字符。此外,=cha[6] 设置为 'Dieck',这不会发生,因为 'Dieck' 不是有效字符。要比较它们,您需要 == 但您一次只能比较一个字符,例如 cha[0] == 'D'

你真的应该让你的输入成为一个字符串,然后使用字符串的 compare() 方法。

std::string input;
// stuff
cin >> input;

if (input.compare("Dieck") == 0)
{
   // more stuff
}

level-1; 计算 level-1 的值,然后将其丢弃,实际上什么都不做。因此,level 中的值永远不会更新,并且您陷入无限循环(您也在对所有变量更新进行此操作,小心!)

如果要递减 level 的值(减一),可以执行以下任一操作:

level = level - 1;
level -= 1;
level--;

此外,if(cha[6] = 'Dieck')在几个方面也不正确。你也许可以做

if(strcmp(cha, "Dieck") == 0) { //...

如果您确定#include <cstring>

你有两个主要问题可能会导致编译错误。

nr+1;
level-1;

您必须将它们分配给某个变量。试试这个:

nr = nr+1;

nr++;

level = level -1;

level--;

现在 while 循环不会 无限循环

第二个问题是

if (cha[6] = 'Dieck' )

请注意,= 是赋值运算符,而不是 等于运算符 。等于运算符看起来像 double equal ==。如果你想比较 cha 是否等于 Dieck,试试这个:

if (strcmp (cha, "Dieck") == 0)

但是您需要为此添加 #include<cstring>

引用here.

2011 版

std::strings,std::binds 初始值设定项列表,现代随机数生成器,auto 变量类型。糟糕,甚至还有一些像 类 和错误检查输入这样的老歌。

#include <iostream>
#include <random>
#include <functional>
#include <map>

// prep random number generator to simulate a 100 sided die
std::default_random_engine engine; // not being fancy here. Just using default RNG
std::uniform_int_distribution<int> uniform(1,100);// random from 1 to 100
auto d100 = std::bind ( uniform, engine ); // Convenience wrapper

void upstat(int & stat, // stat to increase
            int chance, // odds of increase
            int inc, // amount to increase
            const std::string & statname)
{
    if (d100() <= chance)
    { //less than or equal because I decided to emulate a d100.
      // if the range was 0 - 99, only < would be necessary.
      // such is the cost of slavishly adhering to dice conventions.
//        std::cout<< statname << " increased by " << inc << std::endl;
        stat += inc;
    }
}

class Character
{
public:
    Character(const std::string & name,
              int level,
              int HP,
              int str,
              int skl,
              int spd,
              int lck,
              int def,
              int res):
                  mName(name), mLevel(level), mStr(str), mSkl(skl), mLck(lck),
                  mDef(def), mRes(res), mHP(HP), mSpd(spd)
    {

    }

    void levelup()
    {
        upstat(mHP, 90, 1, "HP");
        upstat(mStr, 40, 1, "Strength/Magic");
        upstat(mSkl, 40, 1, "Skill");
        upstat(mSpd, 30, 1, "Speed");
        upstat(mLck, 35, 1, "Luck");
        upstat(mDef, 20, 1, "Defense");
        upstat(mRes, 15, 1, "Resistance");
        mLevel++;
    }

    // a couple useful getters
    const std::string & getName()
    {
        return mName;
    }
    unsigned int getLevel()
    {
        return mLevel;
    }

    // out stream operator
    friend std::ostream & operator<<(std::ostream & out,
                                     const Character & ch)
    {
        out << "Stats " << "HP/STR/SKL/SPD/LCK/DEF/RES " <<
                ch.mHP << " " <<
                ch.mStr << " " <<
                ch.mSkl << " " <<
                ch.mSpd << " " <<
                ch.mLck << " " <<
                ch.mDef << " " <<
                ch.mRes << std::endl;
        return out;
    }

private:
    std::string mName;
    unsigned int mLevel;
    int mStr;
    int mSkl;
    int mLck;
    int mDef;
    int mRes;
    int mHP;
    int mSpd;
};

// name-indexed list of characters. Currently only contains Dieck.
std::map<std::string, Character> charlist{{"Dieck",{"Dieck",1, 26, 9, 12, 10, 4, 6, 1}}};

int main()
{
    unsigned int finalLevel;
    std::string cha; // using a string rather than a char array. Much less error prone.
    std::cout << "Which character?" <<std::endl;
    std::cin >> cha;
    auto found = charlist.find(cha); // look in charlist for selected character
    if (found != charlist.end()) // find returns end of list if not found
    {
        std::cout << "You chose " << found->second.getName() << "." << std::endl <<
                     found->second << std::endl; //optional. Print stats
        for ( ; ; ) // Stay a while. Stay FOREVER! Muhuhahahahaha!
        {
            std::cout << "What level do you want him/her to be?" << std::endl;
            if (std::cin >> finalLevel)
            {
                while (found->second.getLevel() < finalLevel)
                { // keep calling characer's level up routine until desired level reached
                  // or do nothing if the character is already a higher level.   
                    found->second.levelup();
                }
                std::cout << found->second << std::endl; //optional. Print new stats
                break; // breaks the infinite loop if input was good
            }
            else
            { // bad user input. Call user names until they get it right.
                std::cout << "Valid positive numbers only, please." << std::endl;
                std::cin.clear();
                std::cin.ignore(INT_MAX, '\n');
            }
        }
    }
    else
    { // didn't find character. Do nothing.
      // Should probably prompt to create new character here.
        std::cout << "Character " << cha << " not found." << std::endl;
    }
    return 0;
}

2020 反思

变化不大,但将 std::bind 替换为 Lambda 表达式。

std::default_random_engine engine; 
std::uniform_int_distribution<int> uniform(1,100);
auto d100 = std::bind ( uniform, engine ); 

替换为

auto d100 = [](){
    // all bundled up inside the lambda. No globals leaking out
    static std::mt19937 gen{std::random_device{}()}; 
    // explicitly specified the generator. Fewer surprises.
    // this can be expensive, so it might be worth exposing gen and sharing it with 
    // other die-rolling lamdas

    static std::uniform_int_distribution<int> uniform(1,100); // random from 1 to 100

    return uniform(gen); // return result
};