c – 我的程序永远循环,只做我告诉它的一半
作者:互联网
我是编程的新手,我开始制作自己的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,infinite-loop 来源: https://codeday.me/bug/20190928/1825513.html