我在C++上創建基於文本的風險遊戲。一直試圖實現骰子/戰鬥功能,但它一直給我錯誤「f未經初始化使用!」這很奇怪,因爲我早些時候初始化了它。這裏是我的代碼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的關鍵部分。
幾個方面的注意事項:1)在一行中聲明多個變量可能是一個危險的習慣,因爲發生的事情並不總是匹配看起來應該發生的事情。 'int * a,b,c;'聲明一個指向int和兩個int的指針,而不是聲明三個指向int的指針。 2)「骰子」是「死」的複數,就像在遊戲中經常出現的那樣。 「骰子」是一個與切割東西有關的動詞。 – 8bittree