weixin_63226529 2022-04-20 13:40 采纳率: 75%
浏览 97
已结题

求这个问题的做法,为什么我做的输出一直是no solution

问题遇到的现象和发生背景

img

问题相关代码,请勿粘贴截图

#include<stdio.h>
int main()
{
int m, n, w, f, d;
printf("Input the number of matches:\n");
printf("Input the score:\n");
scanf("%d%d",&m,&n);
for(d=1;d<=n;++d);
{
for(w=0;w<=(n-d)/3;++w)
f=n-3w-d;
if(3
w+d==n&&f+d+w==m)
printf("win:%d,draw:%d,fail:%d",w,d,f);
else
printf("No solution!");
}
return 0;
}

运行结果及报错内容
我的解答思路和尝试过的方法
我想要达到的结果
  • 写回答

3条回答 默认 最新

  • 小公鸡卡哇伊呀~ 2022-04-20 14:40
    关注

    使用穷举法,win draw fail 的次数全部都在 0 和 m 之间,使用3重循环,寻找所有可能, 如果积分之和为n,并且场数之和为m,那么就是一种 solution,写法可以是:

    #include<stdio.h>
    int main()
    {
        int m, n, w, f, d;
        printf("Input the number of matches:\n");
        scanf("%d",&m);
        printf("Input the score:\n");
        scanf("%d", &n);
        int hasSolution = 0;
        for (int win = 0; win <= m; win++) 
            for (int draw = 0; draw <= m; draw++) 
                for (int fail = 0; fail <= m; fail++) 
                    if (win + draw + fail == m && win * 3 + draw * 1 == n ) {
                        printf("win: %d, draw: %d, fail: %d\n", win, draw, fail);
                        hasSolution = 1;  // solution 存在,同时修改此变量的值。
                    }
       
        if (hasSolution == 0)   // hasSolution 没有被修改过,仍然为0,solution 不存在。
            printf("no solution");
            
        return 0;
    }
    

    运行结果:
    Input the number of matches:
    6
    Input the score:
    10
    win: 2, draw: 4, fail: 0
    win: 3, draw: 1, fail: 2

    ...Program finished with exit code 0
    Press ENTER to exit console.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 4月28日
  • 已采纳回答 4月20日
  • 创建了问题 4月20日