#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(3w+d==n&&f+d+w==m)
printf("win:%d,draw:%d,fail:%d",w,d,f);
else
printf("No solution!");
}
return 0;
}
使用穷举法,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.
这能编译?
没有C语言环境,就用java写了一个,仅供参考吧
public static void fun2(){
List<String> list=new ArrayList<String>();//用于保存结果
int n=19;//得分
int m=6;//场次
int w=0;//胜场
int d=0;//平场
int f=0;//负场
for(w=0;w<=m;++w){
for(d=0;d<=m;++d){
f=m-w-d;
if(f>=0&&3*w+d==n){//判断得分是否正确
list.add(w+";"+d+":"+f);
}
}
}
if (list.size()>0){
for (String s:list) {
System.out.println(s);
}
}else {//没有正确结果,返回no
System.out.println("No solution!");
}
}