我有一个我试图运行的程序。它编译但没有按预期运行(它仅部分运行):
#include <stdio.h>
int main(int argc, const char * argv[]) {
char play;
char choice;
char answer;
printf("Welcome to Two doors.\n");
printf("Would you like to play? (y/n): ");
scanf("%c", &play);
if (play == 'y') {
printf("\nYou are a prisoner in a room with 2 doors and 2 guards.\n");
printf("One of the doors will guide you to freedom and behind the other is a hangman --you don't know which is which.\n");
printf("One of the guards always tells the truth and the other always lies. You don't know which one is the truth-teller or the liar either.\n");
printf("You have to choose and open one of these doors, but you can only ask a single question to one of the guards.\n");
printf("What do you ask so you can pick the door to freedom?\n\n");
printf("\t1.Ask the truth-guard to point to the door of doom.\n");
printf("\t2.Ask the liar-guard to point to the door of doom.\n");
printf("\t3.Doesn't matter which one you pick.\n");
scanf("%c", &choice);
char answer = "No matter which one you choose the guards both tell you which door leads to death, and therefore you can pick the other door.\n";
switch (choice) {
case 1:
printf("%c", answer);
break;
case 2:
printf("%c", answer);
break;
case 3:
printf("%c", answer);
break;
default:
break;
}
}
return 1;
}
似乎我无法让代码完整地运行。这是我在进入&#39; y&#39;之后运行它时得到的。问题:
Welcome to Two doors.
Would you like to play? (y/n): y
You are a prisoner in a room with 2 doors and 2 guards.
One of the doors will guide you to freedom and behind the other is a hangman --you don't know which is which.
One of the guards always tells the truth and the other always lies. You don't know which one is the truth-teller or the liar either.
You have to choose and open one of these doors, but you can only ask a single question to one of the guards.
What do you ask so you can pick the door to freedom?
1.Ask the truth-guard to point to the door of doom.
2.Ask the liar-guard to point to the door of doom.
3.Doesn't matter which one you pick.
(lldb)
有没有人可以帮我解决这个问题?
谢谢!
答案 0 :(得分:1)
char answer = "No matter which one you choose the guards both tell you which door leads to death, and therefore you can pick the other door.\n";
这当然是错的。 answer
是char
,只能包含单个字符而非字符串文字。
您需要使用char *
或char []
并使用%s
进行打印。
答案 1 :(得分:0)
answer
是char
类型变量,您无法为其指定字符串。
答案 2 :(得分:0)
answer
需要具有const char *
类型。switch (choice) { case 1:
更改为switch (choice) { case '1':
答案 3 :(得分:0)
问题在于,当用户按下Enter键表示他们想要播放时,他们实际上正在发送第二个字符。因此,choice
设置为\n
。
有一些事情需要改变:
char answer = "...
- &gt; char answer[] = "...
'
放在数字周围(例如1
- &gt; '1'
)我对第3号的第一个想法是这样的:
do{
scanf("%c", &choice);
} while(choice != '1' && choice != '2' && choice != '3');
答案 4 :(得分:0)
printf()
部分中的switch
语句缺少换行符(\n
)。根据您的终端,这可能会导致输出被隐藏。使用:printf("%c\n", answer);