使用C语言编写基础传教士与野人代码
时间: 2023-06-08 12:06:57 浏览: 129
好的,我会为您提供基础传教士与野人代码。以下是使用C语言编写的基础传教士与野人代码:
#include <stdio.h>
int main() {
int boats = 1; // 初始化船只数量为1
int missionaries = 3; // 初始化传教士数量为3
int cannibals = 3; // 初始化野人数量为3
while (missionaries > 0 || cannibals > 0) { // 当还有传教士或野人时
printf("There are %d missionaries and %d cannibals on the starting side.\n", missionaries, cannibals);
printf("There are %d missionaries and %d cannibals on the destination side.\n", 3-missionaries, 3-cannibals);
int sent_missionaries, sent_cannibals;
printf("How many missionaries do you want to send across? ");
scanf("%d", &sent_missionaries);
printf("How many cannibals do you want to send across? ");
scanf("%d", &sent_cannibals);
if (boats == 1 && (sent_missionaries > boats || sent_cannibals > boats)) {
printf("You can only send one or two people on the boat.\n");
continue;
}
if ((missionaries-sent_missionaries) < (cannibals-sent_cannibals) && (missionaries-sent_missionaries) > 0) {
printf("The missionaries will be eaten!\n");
continue;
}
boats = boats * -1;
missionaries = missionaries - sent_missionaries * boats;
cannibals = cannibals - sent_cannibals * boats;
}
printf("Congratulations! You have successfully brought all the missionaries and cannibals across the river!\n");
return 0;
}
这段代码是一个简单的命令行程序,它模拟了基础传教士与野人问题。程序首先初始化了一艘船,三个传教士和三个野人。然后它进入一个循环,直到所有传教士和野人都被带到对岸。
在每次循环中,程序打印出当前岸上的传教士和野人数量,以及对岸的传教士和野人数量。然后,它要求用户输入要送过河的传教士和野人数量。如果输入的数量无效(超过船只数量、未能保持传教士数量不低于野人数量等),程序会要求用户重新输入。如果输入的数量有效,程序就将传教士和野人从当前岸送到对岸。
最后,程序输出祝贺信息,表示所有传教士和野人都被安全地送到了对岸。
希望这个代码可以对您有所帮助!
阅读全文