现在的位置: 首页 > 综合 > 正文

C语言练习 表达式的递归计算

2018年01月11日 ⁄ 综合 ⁄ 共 765字 ⁄ 字号 评论关闭

在1 2 3 4 5 6 7 8 9 之间的8个空之间填入“+”“-”“ ”三种,使表达式的值为110。比如1 2之间填入的是“ ”,则他们成为12。8个都是“ ”则表达式的值为123456789。

输出所有的情况,使表达式的值为110。

#include <STDIO.H>
#include <string>
#include <stdlib.h>
using namespace std;
int total;

void print(string str)
{
	printf("%d:",total++);
	int i=0,len=str.length();
	while(i<len&&str[i]!='1') i++;
	for (;i<len;i++)
	{
		printf("%c",str[i]);
	}
	printf("=110\n");
}
string atos(int n)
{
	if (n==0)
	{
		return "0";
	}
	string str="";
	int N=1000000000;
	while (n/N==0)
	{
		N=N/10;
	}
	while (n>0)
	{
		str+=char('0'+n/N);
		n=n%N;
		N=N/10;
	}
	return str;
}
void function(int cur,int pre,string str,int result)
{
	if (result==110&&cur>10)
	{
		print(str);
	}
	else if (cur>10)
	{
		return;
	}
	else
	{
		function(cur+1,pre*10+cur,str,result);
		function(cur+1,cur,str+"+"+atos(pre),result+pre);
		function(cur+1,cur,str+"-"+atos(pre),result-pre);
	}

}

int main()
{
	function(0,0," ",0);
	return 0;
}

抱歉!评论已关闭.