我是编程的新手,我开始制作自己的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
}

关于c++ - 我的程序永远循环,只执行我告诉它要做的一半,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31059976/

10-10 21:38