用程序解决生活中的“选择困难症”

今天和大家分享一个有趣的程序,博主编写这个程序是为了用程序帮我们做出生活中的那些困难的选择。


某参观团按以下条件限制从A、B、C、D、E五个地方中选定若干参观点:

    • 如去A则必须去B;
    • D、E两地只能去一地;
    • B、C两地只能去一地;
    • C、D两地都去或都不去;
    • 若去E地,A、D也必去。

问该团最多能去几个地方?是哪几个地方?


分析:

  • 用变量a, b, c, d, e 表示五个地点。变量的值为1,则表示去;变量的值为0,则表示不去。
  • 根据题意可写出表达式:
          a+b==2 || a==0;
d+e != 2;
b+c != 2;
c+d==0 || c+d==2;
e+a+d==3 || e==0.

程序:
#include <stdio.h>

int main()
{
    int a, b, c, d, e, count = 0, num, max = 0, ccount = 0, i;
    int array[5][6] = {0};

    for (a = 1; a >= 0; a--)    //穷举所有情况
        for (b = 1; b >= 0; b--)
            for (c = 1; c >= 0; c--)
                for (d = 1; d >= 0; d--)
                    for (e = 1; e >= 0; e--)
                    {
                        if ((a+b == 2 || a == 0) &&
                            d+e != 2 &&
                            b+c != 2 &&
                            (c+d == 0 || c+d == 2) &&
                            (e+a+d == 3 || e == 0))    //符合条件的情况
                        {
                            count++;    //计数
                            num = a+b+c+d+e;    //计算能去几个地方
                            *(*(array + count)) = num;    //二维数组每一行存储一种情况
                            *(*(array + count)+1) = a;
                            *(*(array + count)+2) = b;
                            *(*(array + count)+3) = c;
                            *(*(array + count)+4) = d;
                            *(*(array + count)+5) = e;    //每行的第一列存储该情况能去几个地方,每行二至六列存储该情况a~f对应的值
                            if (num > max)    //比较,得出最多能去几个地方
                            {
                                max = num;
                            }
                        }
                    }

                    printf("\nThey can visit %d places at most.\n\n", max);
                    for (i = 0; i < 5; i++)
                    {
                        if (max == *(*(array+i)))    //若此情况为 去的地方最多 的情况,打印
                        {
                            printf("plan %d :\n", ++ccount);
                            printf("They will%s go A.\n", *(*(array+i)+1) ? "" : " not");
                            printf("They will%s go B.\n", *(*(array+i)+2) ? "" : " not");
                            printf("They will%s go C.\n", *(*(array+i)+3) ? "" : " not");
                            printf("They will%s go D.\n", *(*(array+i)+4) ? "" : " not");
                            printf("They will%s go E.\n", *(*(array+i)+5) ? "" : " not");
                            printf("\n");
                        }
                    }

    return 0;
}



结果:


这样的程序是不是既实用又有趣呢?
今天就到这里啦,大家晚安!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值