我在C ++上创建基于文本的风险游戏。一直试图实现骰子/战斗功能,但它一直在给我错误" f在没有初始化的情况下使用!"这很奇怪,因为我之前已将其初始化。这是我的代码
void battle(int attack, int defend)
{
int a, b, c, d, e, f;
if (attack >= 3)
{
a = rollDice();
b = rollDice();
c = rollDice();
}
else if (attack == 2)
{
a = rollDice();
b = rollDice();
c = 0;
}
else if (attack == 1)
{
a = rollDice();
b = 0;
c = 0;
}
else if (defend >= 2)
{
d = rollDice();
e = rollDice();
f = 0;
}
else if (defend == 1)
{
d = rollDice();
e = 0;
f = 0;
}
sortValues(a, b, c);
sortValues(d, e, f);
cout << endl << "The attacking country rolled the following dices: " << a
<< " " << b << " " << c << ".";
cout << endl << "The defending country rolled the following dices: " << d
<< " " << e << " " << f << ".";
if (a == d)
{
attack = attack - 1;
}
else if (a != d)
{
if (a < d)
{
attack = attack - 1;
}
else if (a > d)
{
defend = defend - 1;
}
}
else if (b == e)
{
attack = attack - 1;
}
else if (b != e)
{
if (b < e)
{
attack = attack - 1;
}
else if (b > e)
{
defend = defend - 1;
}
}
// since the int f is never used, this function is critical to implement. so that we can avoid compile time error
_unused(f);
}
int main()
{
int attack;
int defend;
int choice;
// this asks for the user choice of what he would like to do.
cout << "How large is the attacking army?" << endl;
cin >> attack;
cout << "How large is the defending army?" << endl;
cin >> defend;
while (attack >= 1 && defend >= 1)
{
cout
<< "Based on the numbers you entered, you have a couple of choices: "
<< endl << endl;
cout << "1) Battle once" << endl;
cout << "2) Battle until the end" << endl;
cout << "3) Withdraw from the battle" << endl;
cout << "Please enter your game choice (just enter the number): "
<< endl;
cin >> choice;
if (choice == 1)
{
battle(attack, defend);
}
if (choice == 2)
{
do
{
battle(attack, defend);
} while (attack != 0 && defend != 0);
cout << "Battle ended. The attacking forces are: " << attack
<< " , while the defending forces are: " << defend << endl;
}
if (choice == 3)
{
break;
}
}
if (attack < 1)
{
cout
<< "The attacking forces have lost. Defending forces keep their territory"
<< endl;
}
else if (defend < 1)
{
cout << "The attacking forces have won over the territory." << endl;
}
system("pause");
return 0;
}
这不是所有代码,但它是包含和使用f的关键部分。
答案 0 :(得分:0)
在battle
函数中调用sortValues(d,e,f)
,但在前3个if-cases f
中没有得到值(因此未初始化)。
实际上你应该为d
收到类似的错误(是真的是错误还是警告?),在某些情况下,你没有给a
b
,{{1} }和c
。