首页 > 解决方案 > 嵌套的 for 循环现在不起作用

问题描述

我现在的代码大部分都在工作。但是,当运行嵌套 for 循环时,轮数不会改变。我哪里出错了?另外我如何将健康变化存储在各个变量中?

for (int round = 1; round <=30; round++)
{
    int sorceressHealth = 30;// sets health
    int wizardHealth = 30;
    for (int x = 0; x <= ARRAYROW; x++) {


        system("pause");
        //Round begins
        cout << endl << "Round " << round << "  fight!" << endl;


        //Sorceress draws card
        cout << "Sorceress draws " << sorDeck[x].sName << endl;
        //Card attacks Wizard
        cout << sorDeck[x].sName << " deals " << sorDeck[x].sAttk << " damage to Wizard!" << endl;


        //wizard draws card
        cout << "Wizard draws " << wizDeck[x].wName << endl;

        //Card attacks sorceress
        cout << wizDeck[x].wName << " deals " << wizDeck[x].wAttk << " damage to Sorceress!" << endl;


        cout << endl << "Sorceress has:" << sorceressHealth - wizDeck[x].wAttk << " Health" << endl; // displays health
        cout << "Wizard has:" << wizardHealth - sorDeck[x].sAttk << " Health" << endl;

标签: c++arraysloopsfor-loop

解决方案


要回答问题的第二部分,假设每一轮健康都会减少,直到 1 名玩家达到 0。(因为你现在实现它的方式是每次内部 For 循环完成时,你重置巫师和女术士的健康,因此使此要求无用)

在两个循环外声明WizardHealthsorceressHealth

int wizardHP = 30;
int sorceressHP = 30;
for ( int round = 1; round <= 30; round++ ) {
//Do your code execution
     for(int x = 0; x <= ARRAYROW; x++) {
         //Execute fight sequence
         wizardHP -= sorDeck[x].sAttk;  //To store the new hp of wizard
         sorceressHP -= wizDeck[x].wAttk;  //To store the new hp of sorceress
     }
}

这样,每次迭代都将使用更新的变量,而不是从 30 开始。(如果我对您的执行要求有误,请纠正我)

PS您的外部(圆形)循环在我的IDE上完美执行。我看不出有什么问题。


推荐阅读