大卫葛瑞特来过中国吗:C语言编程高手请教啦!

来源:百度文库 编辑:神马品牌网 时间:2024/04/27 20:57:58
我是菜鸟,要交作业了,有个程序不会,请教高手啊。
程序的意思是:输入一个数,然后输出和为这个数的所有组合。要求“+”左边的数不能小于右边的数。
例如:
输入:4 回车
输出:4=3+1
4=2+2
4=2+1+1
4=1+1+1+1
结束
帮帮忙撒!

#include<stdio.h>

int res[100],N,i;

void outres(int no)
{
printf("%d=%d",N,res[1]);
for(i=2;i<no;++i) printf("+%d",res[i]);
printf("\n");
}

void split(int no,int remain)
{
int k;
if (remain==0&&no!=2)
outres(no);
else
{
// k=min(res[no-1],remain)
for (k=res[no-1]>remain?remain:res[no-1]; k>0; --k)
{
res[no]=k;
split(no+1,remain-k);
}
}
}

int main()
{
while(1)
{
scanf("%d",&N);
if(N<=1) break;
res[0]=N;
split(1,N);
}
return 0;
}

分太少了
懒的做啊

自己做了
我们可以帮你修改一哈
完全要我们跟你做
没有那个时间啊

#include "stdio.h"

void main()
{
int n;
scanf("%d", &n);

if (n == 1)
{
printf("1=1\n");
return;
}

if (n == 2)
{
printf("2=1+1\n");
return;
}

int *a = new int(n);
int top = 0;
a[0] = n - 1;
a[1] = 1;
top = 2;

int i;
do{
printf("%d=%d", n, a[0]);
for (i = 1; i < top; i++)
{
printf("+%d", a[i]);
}
printf("\n");

int s = 0;
do{
s += a[--top];
}while (top >= 0 && a[top] == 1);
if (top == -1)
{
break;
}

int d = a[top] - 1;
if (d == 1)
{
while (s > 0)
{
a[top++] = 1;
s--;
}
}
else
{
do{
a[top++] = d;
s -= d;
}while (s >= d);
if (s != 0)
{
a[top++] = s;
}
}
}while (1);
}