3.2 字符数组

习题 3-4 竖式问题

  找出所有形如abc*de(三位数乘以两位数)的算式,使得在完整的竖式中,所有数字都属于一个特定的数字集合。
输入数字集合(相邻数字之间没有空格),输出所有竖式。每个竖式前应有编号,之后应有一个空行。最后输出解的总数。
具体格式见样例输出(为了便于观察,竖式中的空格改用小数点显示,但你的程序应该输出空格,而非小数点)。

  样例输入:

    2357

  样例输出:
    <1>
    ..775
    X..33
    -----
    .2325
    2325.
    -----
    25575
    The number of solutions = 1

程序 3-4 竖式问题

#include<stdio.h>
#include<string.h>
int main()
{
      char s[20], buf[50];
      //scanf("%s", s)与scanf("%d", x)类似,将读取一个不含空格,Tab, 回车的字符串,存入字符数组s中
      //注意区分 scanf("%s", s) 与 scanf("%d", &a[1])
      //注意区分 s 与 &s
      scanf("%s", s);
      int abc, de, d, e, mul, dmul, emul, count = 0;

      for (abc = 100; abc <= 999; abc++)
      {
            for (de = 10; de <= 99; de++)
            {
                  d = de / 10;
                  e = de % 10;
                  dmul = d * abc;
                  emul = e * abc;
                  mul = abc * de;

                  //sprintf()将数据输出到数组中
                  sprintf(buf, "%d%d%d%d%d", abc, de, dmul, emul,mul);

                  int ok = 1;
                  for (int i = 0; i <= strlen(buf); i++)
                  {
                        //char *strchr(const char* _Str,int _Val)
                        //char *strchr(char* _Str,int _Ch)
                        //头文件:#include <string.h>
                        //功能:查找字符串s中首次出现字符c的位置
                        // 说明:返回首次出现c的位置的指针,返回的地址是被查找字符串指针开始的第一个与Val相同字符的指针,如果s中不存在c则返回NULL。
                        //返回值:成功则返回要查找字符第一次出现的位置,失败返回NULL
                        if (strchr(s, buf[i]) == NULL)
                        {
                              ok = 0;
                              break;
                        }
                  }

                  if (ok)
                  {
                        printf("<%d>\n", ++count);
                        //也可以分7行输出,比较直观
                        printf("%5d\nX%4d\n-----\n%5d\n%4d \n-----\n%5d\n\n", abc, de, dmul, emul, mul);
                  }
            }
      }
            printf("The number of solutions = %d", count);
}

 

有关 sprintf(), strchr() 函数,详情百度百科。

 

posted @ 2015-07-10 18:55  Traim304  阅读(118)  评论(0编辑  收藏  举报