C++经典编程题目(一)算数计算竖式

1. 给定等式

               A B C D E      
                   D F G      
             +     D F G     
            ─────────────
                X Y Z D E
      

其中每个字母代表一个数字,且不同数字对应不同字母。编程求出这些数字并且打出这个数字的算术计算竖式。

#include 
#include 
using namespace std;

/*
  A B C D E
      D F G
+     D F G
──────
  X Y Z D E
*/

void printNum(int A, int B, int C, int D, int E, int F, int G, int X, int Y, int Z)
{
     
	printf("%2d%2d%2d%2d%2d\n", A, B, C, D, E);
	printf("%*d%2d%2d\n", 6, D, 5, 0);
	printf("+%*d%2d%2d\n", 5, D, 5, 0);
	printf("%10s------------\n", "------------");
	printf("%2d%2d%2d%2d%2d\n", X, Y, Z, D, E);
}

int main()
{
     
	int A, B, C, D, E, F, G, X, Y, Z;
	E = 0;
	//(DE+FG+FG)%100=DE ->FG=50
	F = 5; 
	G = 0;
	//Z = (C+D+D+1)%10 && Z !=0
	//Y = (B+(C+D+D+1)/10)%10 
	//X !=A && X=A+1
	//(B+(C+D+D+1)/10)>10 &&  1 <= (C+D+D+1)/10 <= 2  && Y != 0  -> (C+D+D+1)/10 = 2 && B=9 
	//-> (C + D + D + 1)>20 -> C>=5 && D>=5
	B = 9;
	//E = 45 - (A + 9 + C + D + E + 5 + 0 + X + Y + Z) = 31 - A - C - D - X - Y - Z

	for (A = 1; A < 9; A++)
	{
     
		if (A == 5)
			continue;
		for ( C = 5; C < 9; C++)
		{
     
			if (C == A)
				continue;
			for (D = 5; D < 9; D++)
			{
     
				if ((D == A) || (D == C))
					continue;
				X = A + 1;
				Y = (B + (C + D + D + 1) / 10) % 10;
				Z = (C + D + D + 1) % 10;
				E = 31 - A - C - D - X - Y - Z;
				if (((A != B) && (A != C) && (A != D) && (A != E) && (A != F) && (A != G) && (A != X) && (A != Y) && (A != Z))
					&& ((B != C) && (B != D) && (B != E) && (B != F) && (B != G) && (B != X) && (B != Y) && (B != Z))
					&& ((C != D) && (C != E) && (C != F) && (C != G) && (C != X) && (C != Y) && (C != Z))
					&& ((D != E) && (D != F) && (D != G) && (D != X) && (D != Y) && (D != Z))
					&& ((E != F) && (E != G) && (E != X) && (E != Y) && (E != Z))
					&& ((F != G) && (F != X) && (F != Y) && (F != Z))
					&& ((G != X) && (G != Y) && (G != Z))
					&& ((X != Y) && (X != Z))
					&& (Y != Z)
					&& (A * 10000 + B * 1000 + C * 100 + D * 10  + 2 * (D * 100 + F * 10) == 10000 * X + 1000 * Y + 100 * Z + 10 * D ))
				{
     
					printNum(A, B, C, D, E, F, G, X, Y, Z);
				}
			}
		}
	}

	system("pause");

	return 0;
}

用数组可以更高效的完成循环,这里为了表示清楚所以用了独立的变量;

你可能感兴趣的:(C++学习笔记)