我想要一個無限回圈,這很有效。但我不知道為什么它會兩次列印出同一行。有什么想法嗎?
輸出:
最后選擇: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");
}
}
}
uj5u.com熱心網友回復:
這是因為當您輸入您的密鑰然后按 Enter 鍵時,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");
}
}
}
uj5u.com熱心網友回復:
我想我已經為你作業了!
#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: ");
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/455494.html
