“程序已停止工作”

时间:2013-10-31 07:53:50

标签: c arrays string for-loop while-loop

当我运行程序时,第一个for循环工作正常,但在进入第二个"Program has stopped working"循环之前我得到while消息。我的编码是否有错误,如果有,我该如何解决?

#include<stdio.h>

double Combat(int x, int y, char mons[20]);


int  main(void)
{
    int monsters, i, target, alive;

    while(1)
    {
        printf("ENTERING COMBAT\n\nHow many monsters?> ");
        scanf(" %d", &monsters);
        char monster[monsters][20];
        int monstermaxhp[monsters];
        int monsterhp[monsters];
        for(i=0;i<monsters;++i)
        {
            printf("\n\nNO SPACES\n\nEnter Monster %d's name> ", i+1);
            scanf("%s", &monster[i]);
            printf("\n\nEnter %s's hitpoints> ", monster[i]);
            scanf("%d", &monstermaxhp[i]);
            monsterhp[i]=monstermaxhp[i];
        }
            alive=1;
            while(alive==1)
        {
          for(i=0;i<monsters;++i)
        {
            printf("\n\n%d:%s%3c%3d/%d", i+1, ' ',monsterhp[i],monstermaxhp[i]);
        }
        printf("\n\nSelect Target> ");
        scanf("%d", &target);
        i=target-1;
        monsterhp[i]=Combat(monsterhp[i],monstermaxhp[i],monster[i]);
        for(i=0;i<monsters;++i)
        {
            if(monsterhp[i]<=0)
                alive=0;
        }
        }
    }
    return(0);
}


double Combat(int x, int y, char mons[20])
{
    int damage, plrroll, monroll;

    printf("\nRoll for %s> ", mons);
    scanf("%d", &monroll);
    printf("\nRoll for Player> ");
    scanf("%d", &plrroll);
    if(plrroll>monroll)
    {
        printf("\nHIT! Roll for damage> ");
        scanf("%d", &damage);
        x=x-damage;
    }
    else
    {
        printf("\nMISS! :P\n");
    }
    return(x);
}

2 个答案:

答案 0 :(得分:2)

变化:

printf("\n\n%d:%s%3c%3d/%d", i+1, ' ',monsterhp[i],monstermaxhp[i]);

printf("\n\n%d: %s   %3d/%d", i+1, monster[i], monsterhp[i], monstermaxhp[i]);

你正试图以错误的顺序打印。我想你错过了怪物的名字!使用%c也不需要3个空格,所以我已经在格式字符串中插入了空格。

您现在获得如下输出:

  

1:好1/1

     

2:邪恶2/2

答案 1 :(得分:0)

好吧,您的代码只有一些问题:

  1. 你在每次在外面循环时声明数组:monster,monstermaxhp和monsterhp

  2. 不是return(0); .. return 0;

  3. for循环中的
  4. 执行后递增(将++i更改为i++

  5. 修正你的printf语句:

    printf("\n\n%d:%s%3c%3d/%d", i+1, monsterhp[i], ' ', monstermaxhp[i]);

  6. 同时更改:

    scanf("%s", &monster[i]);

    到此:

    scanf("%s", monster[i]);