- d终端输入打印行数,打印直角三角形
C语言代码
#include <stdio.h>
int main(int argc,const char* argv[])
{
int i,j,rows;
printf("please input rows:");
scanf("%d",&rows);
for(i=0;i<rows;i++)
{
for(j=i;j>=0;j--)
{
printf("* ");
}
printf("\n");
}
return 0;
}
shell脚本
#!/bin/bash
read -p "please input rows:" row
i=0
while [ $i -lt $row ]
do
j=$i
while [ $j -ge 0 ]
do
echo -n '* '
((j--))
done
echo
((i++))
done
效果
2. 终端输入软件名,之后判断是否下载软件,执行脚本后,如果确认下载输入y,输入其他不下载
#!/bin/bash
read -p "please enter the name of the software:" name
read -p "please enter your choice:" choice
case $choice in
Y|yes|y|YES)
echo "you entered yes,now begin to download the software:$name"
sudo apt-get download $name
;;
N|no|n|NO)
echo "you entered no,nothing will be done"
;;
*)
echo "wrong input"
exit
;;
esac
效果
3. 使用while循环输入99乘法表
C语言
#include <stdio.h>
int main(){
//line control
int i = 0;
//column control
int j = 0;
for(i=1;i<=9;i++){
for(j=1;j<=i;j++){
printf("%dx%d=%d\t",j,i,i*j);
}
printf("\n");
}
}
shell
#!/bin/bash
i=1
while [ $i -le 9 ]
do
j=1;
while [ $j -le $i ]
do
echo -n "${j}x${i}=$((i*j)) "
((j++))
done
echo
((i++))
done
输出效果
4. 完成四则运算 输入5+4输出9 输入5-4输出1
#!/bin/bash
read -p "please enter the expression:" var
#echo $var
pos_plus=`expr index $var "\+"`
pos_minus=`expr index $var "\-"`
if [ $pos_plus -ne 0 ]
then
#echo +
op1=$(expr substr $var 1 $((pos_plus-1)))
#echo $op1
op2=$(expr substr $var $((pos_plus+1)) `expr length $var`)
#echo $op2
echo $var=$((op2+op1))
fi
if [ $pos_minus -ne 0 ]
then
op1=$(expr substr $var 1 $((pos_minus-1)))
#echo $op1
op2=$(expr substr $var $((pos_minus+1)) `expr length $var`)
#echo $op2
echo $var=$((op1-op2))
fi
效果: