簡體   English   中英

為什么我的 c 代碼會重復第一個 printf 行?

[英]Why does my c code repeat the first printf line?

我想要一個無限循環,這很有效。 但我不知道為什么它兩次打印出同一行。 有什么想法嗎?

output:

最后選擇:p
你的下一步:RL最后的選擇:最后的選擇:l
最后選擇: 最后選擇:r
你的下一步:SL 最后的選擇: 最后的選擇:

到目前為止,這是我的代碼:

#include <stdio.h>
#include <cs50.h>

int main ()
{
    while (true)
    {
// Prompt user for input last choice contender
        char c;
        printf("Last choice: ");
        c = getchar();
      // If last choice is R, loser should play S
        if (c == 'R'|| c == 'r')
        {
            printf("Your next move: S");
        }
// Else if last choice is P, loser should play R
        else if (c == 'P' || c == 'p')
        {
            printf("Your next move: R");
        }
// Else if last choice is S, loser should play P
        else if (c == 'S' || c == 's')
        {
            printf("Your next move: P");
        }
    }
}

我想我已經為你工作了!

#include <stdio.h>
int main () {
    printf("Last choice: ");
    while (1) {
        char c;
        c = getchar();
        if(c != '\n')
        {
            if (c == 'R'|| c == 'r') {
                printf("Your next move: S\n");
            } else if (c == 'P' || c == 'p') {
                printf("Your next move: R\n");
            } else if (c == 'S' || c == 's') {
                printf("Your next move: P\n");
            } else {
                printf("Use valid input\n");
            }
            printf("Last choice: ");
        }
    }
}

這是因為當您輸入密鑰然后按回車鍵時,getchar 會正確獲取您的密鑰,並且還會得到一個\n ,這是您的回車鍵。 所以你只需要在你的代碼中添加一點 if 就可以讓它像這樣工作:

#include <stdio.h>
#include <cs50.h>

int main ()
{
    while (true)
    {
// Prompt user for input last choice contender
        char c;
        printf("Last choice: ");
        c = getchar();
        if (c != '\n')
            getchar(); //gets the \n if you've given a letter
      // If last choice is R, loser should play S
        if (c == 'R'|| c == 'r')
        {
            printf("Your next move: S");
        }
// Else if last choice is P, loser should play R
        else if (c == 'P' || c == 'p')
        {
            printf("Your next move: R");
        }
// Else if last choice is S, loser should play P
        else if (c == 'S' || c == 's')
        {
            printf("Your next move: P");
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM