问题描述
一开始题目都没看懂,题目看了好几遍……
找出所有形如abc*de(三位乘两位数)的算式,使得在完整的竖式中,所有数字都属于一个特定的数字集合。输入数字集合(相邻数字之间没有空格),输出所有竖式。每个竖式前应有编号,之后应有一个空行。最后输出解的总数。具体格式见样例输出。(为了便于观察,竖式中的空格改用小数点显示,但所写程序中应该输出空格,而非小数点)。
样例输入:
2357
样例输出:
<1>
..775
x..33
-----
.2325
2325.
-----
25575
The number of solutions = 1
分析:尝试所有的abc和de,判断是否满足条件。
小白分析
目测自己只会蛮力
刘汝佳大神说
本题的思路应该是很清晰的:尝试所有的 abc 和 de,判断是否满足。我们可以写出整个程序的伪代码:
char s[20];
int count = 0;
scanf("%s", s);
for(int abc = 111; abc <= 999; abc++)
for(int de = 11; de <= 99; de++)
if("abc * de" 是个合法的竖式) {
printf("<%d>\n", count);
打印 abc * de 的竖式和其后的空行
count++;
}
printf("The number of solutions = %d\n", count);
注意,scanf(“%s”, s) 遇到空白字符会停下来。
可以一条输出语句打出结果。首先计算第一行乘积 x = abc * e, 然后是 y = abc * d, 最后是总乘积 z = abc * de 。
可以用 %5d 占位输出(还记得 %03d 吗)
小白多嘴
这里不考虑 0 吗?
代码注释
/*
<1> 类比 printf, fprintf, sprintf 指输出到字符串。但应当确保字符串足够大
可以容纳输出的信息。
<2> strchr 的作用是在一个字符串中查找单个字符。注意字符串是以空字符
'\0' 结尾的。
备注:strcpy(a,b), strcmp(a, b), strcat(a, b) 来执行 赋值,比较,连接
操作。上述函数在 string.h 中声明。
*/
#include <stdio.h>
#include <string.h>
int main() {
int count = 0; // 统计找到的符合要求的竖式的个数
char s[20], buf[99]; // buf 用来储存在竖式中出现的所有数
scanf("%s", s); // 输入数字集合,保存到 s 数组
for(int abc = 111; abc <= 999; abc++) {
for(int de = 11; de <= 99; de++) {
int x = abc * (de % 10), y = abc * (de / 10), z = abc * de;
// 把竖式中的数依次存到 x, y, z 中
// 最后所有在竖式中出现的数 都存在 buf 中
sprintf(buf, "%d%d%d%d%d", abc, de, x, y, z); // <1>
// sprintf 用来把 "%d%d%d%d%d" 所表示的数 打印输出到 buf 字符数组中
int ok = 1;
for(int i = 0; i < strlen(buf); i++) { // strlen 是返回 buf 数组的有效实际长度
if(strchr(s, buf[i]) == NULL) ok = 0; // <2> strchr 用来查 buf[i]
// 是否存在与 s 字符数组中。
}
if(ok) {
printf("<%d>\n", ++count);
printf("%5d\nX%4d\n-----\n%5d\n%4d\n-----\n%5d\n\n", abc, de, x, y, z);
}
}
}
printf("The number of solutions = %d\n", count);
return 0;
}
还是得闭眼思考一下
学到了几个 string.h 中的函数,比如 strlen, strcpy, strcmp, strcat, strchr, sprintf.
努力前进吧,每天多学一点点,抓住现在,不念过去,不畏将来!