代码永远不会被执行C.

时间:2015-08-30 01:47:53

标签: c macos

我有这个问题,它说if if(knightATKC == 2&& knightATKC == 4)我说代码永远不会被执行。它将无法正常工作。如果有人知道如何解决这个问题会很棒。不要担心你可能会看到的未使用的变量,我将在最后使用,但现在我不知道如何修复代码永远不会被执行。抱歉我的英语不好:/

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>

int main()
{
char enter = 0;
char pNAME[30];
char pGENDER;
int pAGE;
int pATK;
int pHP = 20;
int pATKC;
int knightATK = 3;
int knightHP = 15;
int knightATKC = 0;
int kingATK = 5;
int kingHP = 30;
int kingATKC;

printf("While you are enjoying your breakfast at your house, suddenly you get teleported to a different dimension and no one to be seen except an old man.\n");
printf("\nOld Man: What is your name warrior?\n");
printf("\nInsert name:\n");
scanf("%s",pNAME);
fpurge( stdin );

printf("\nInsert gender (m/f):\n");
scanf("%c",&pGENDER);
fpurge( stdin );
while ( pGENDER != 'f' &&pGENDER != 'm' )
{
    printf("\nInvalid entry, please try again.\n");
    printf("\nInsert gender (m/f):\n");
    scanf("%c",&pGENDER);
}

printf("\nOld Man: Now how old are you young warrior?\n");
printf("\nInsert Age:\n");
scanf("%d",&pAGE);
fpurge( stdin );
if ( pAGE < 18)
{
    printf("\nOy mate! No stalker!\n");
    printf("\nTeleporting back to reality...\n");

    return 0;
}

if ( pAGE > 80)
{
    printf("\nNo oldies allowed!\n");
    printf("\nTeleporting back to reality...\n");

    return 0;
}

printf("\nOld Man: Welcome warrior I fear the knights has taken over our kingdom, and you, %s, are the only one who can save us.\n",pNAME);
printf("\n%s: How am I suppose to do that?[Enter]\n",pNAME);
if (enter != '\r' && enter != '\n') { enter = getchar(); }
printf("HI");

while (pHP != 0 && knightHP != 0)
{
    pATK = 5;
    knightATK = 3;

    knightATKC = ( rand()%5);

    if (knightATKC == 2 && knightATKC == 4)
    {
        printf("The knight swings his sword at %s",pNAME);
        printf("T\nhe knight hits %s for 3HP\n",pNAME);
        pHP = pHP - 3;
    }
    else if (knightATKC == 3)
    {
        printf("\nThe knight slashes his sword at %s\n",pNAME);
        printf("\nThe knight critically hit %s for 5 HP\n",pNAME);
        pHP = pHP - 5;
    }
    else
    {
        printf("\nThe knight swings his sword at %s\n",pNAME);
        printf("\nThe knight fails to hit %s\n",pNAME);
        printf("\nPress [Enter] to attack\n");
    }

}}

2 个答案:

答案 0 :(得分:3)

你的问题不言自明。 knightATKC == 2 && knightATKC == 4表示knightATKC同时为2和4,这是不可能的。也许你的意思是||(布尔或)而不是&&(布尔和)?

答案 1 :(得分:3)

不良陈述:

if (knightATKC == 2 && knightATKC == 4)

这整个if语句永远不会成立,因为&&运算符是&#34;&#34;所以第一次比较和第二次比较都必须是真的。但如果knightATKC等于2,则knightATKC不能等于4

你想要的可能是&#34;或&#34;

if (knightATKC == 2 || knightATKC == 4)

如果其中一种是真的。