您的位置:首页 > 编程语言 > C语言/C++

shell 脚本实现乘法口诀表的两种方法——shell与C语言

2019-11-08 22:54 2516 查看

shell 脚本实现乘法口诀表的两种方法——shell与C语言

话不多说直接给出代码:

1 #!/bin/bash
2 if [ $# -eq 0 ]         //用于判断输入的参数个数为0
3 then
4         echo "welcome you!"
5         echo "this is a test with 2 methods to output arbitrarily mux table!"
6 else
7         echo "sorry you input invliad argc!"
8         echo "you input other argc before!"
9         exit 0         //退出
10 fi
11
12 while ((1))            //创建死循环防止输错给出的命令而退出
13 do
14         echo "you can choose 'shell' 'gcc' or 'quit' command"
15         read -p "please input your choice:" choice
16
17         if  [ $choice == "shell" ]              //判断是shell方法实现
18         then
19                 echo "will do show shell"
20                 read -p "please input a num you want:" num
21                 touch 6.sh
22                 echo "" > 6.sh
23                 echo '#!/bin/bash                //将shell脚本实现的方法写入某个脚本文件中,这里是6.sh
24 for ((j=1;j<=$1;j++))
25 do
26         for((i=1;i<=j;i++))
27         do
28                 echo -ne "$i*$j=$[$i*$j]\t"
29         done
30                 echo -e "\r"
31 done
32 '   >> 6.sh
33                 #chmod 777 6.sh          //看自己是什么用户权限选择这个命令
34                 cat 6.sh
35                 source 6.sh $num         //执行
36                 exit 0
37         elif [ $choice == "gcc" ]        //判断是C语言实现方法
38         then
39                 echo "will do show c"
40                 touch 6.c
41                 echo "" > 6.c
42                 echo '#include<stdio.h>   //将C语言的方法写入到.c文件
43
44
45
46
47 int main(int argc,char **argv)
48 {       if(argc<2)
49                 perror("argc num is not correct!please do it again!");
50         printf("%s\n",argv[1]);
51         int num;
52         num=atoi(argv[1]);
53         int i,j;
54         for (j=1;j<=num;j++)
55         {
56                 for(i=1;i<=j;i++)
57                 {
58                         printf("%d*%d=%d\t",i,j,i*j);
59                 }
60                 printf("\n");
61         }
62
63         return 0;
64 }' >> 6.c
65                 cat 6.c
66                 gcc -o 6 6.c                       //编译过程
67                 read -p "please input a number you want:" number
68                 ./6 $number                        //程序执行
69                 exit 0
70         elif [ $choice == "quit" ]                  //您选择直接退出
71         then
72                 exit 0
73         else
74                 echo "you don't choose a correct choice!"  //表示输错命令可以重新输入
75         fi
76 done
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: