命令行菜单小程序V1.0

这篇博客对应线上课程的第二次实验。

网易云课堂:http://mooc.study.163.com/learn/USTC-1000002006?tid=1000081002#/learn/announce
实验楼:https://www.shiyanlou.com/courses/122
代码库:http://git.shiyanlou.com/chenxu/shiyanlou_cs122

实验思路:

       本次实验要实现一个命令行下的菜单工具,能提示用户输入哪些命令,然后程序根据用户输入的命令输出对应的结果,其中每个命令对应一个函数;

实验过程:

  • 首先写出系统主要逻辑,即用一个循环体来获取用户命令,然后与数组中的命令一一比对,如在数组中查找到该命令,则跳出数组遍历的循环(这么做主要是为了之后根据计数器i的值调用对应函数);
    //char* cmd[]={"sum","pro","squ","cube","evo","log","help","quit"};
    printf("Please input your command:");
    scanf("%s",command);
    for(i=0;i<8;i++)
    {
        if(strcmp(command,cmd[i]) == 0)
        {
            break;
        }
    }
  • 使用switch语句,用上一步得出的i的值作为匹配条件,在不同case下调用不同函数,与之前的数组内容相对应;
    switch(i)
    {
        case 0:
            sum();
            break;
        case 1:
            product();
            break;
       //  。。。省略。。。
        case 6:
            help();
            break;
        case 7:
            quit();
            break;
        default:
            printf("Wrong Command\n");
            break;
    }
  • 这个程序里写了8个命令函数,分别用于求和、求积、平方、立方、开平方、求对数以及帮助和退出;
void help()
{
    printf(" sum    return the sum of the numbers which you input\n");
    printf(" pro    return the production of the numbers which you input\n");
    printf(" squ    return the square of the numbers which you input\n");
    printf(" cube   return the cube of the numbers which you input\n");
    printf(" evo    return the evolution of the numbers which you input\n");
    printf(" log    return the logarithm of the numbers which you input\n");
    printf(" help   output the usage of the program\n");
    printf(" quit   exit the program\n");
}
  • 实验中问题:
           switch语句只能判断整形和单个字符。另外在Linux环境下,用gcc编译含有math库的C文件,需要在编译时添加-lm命令,像这样
gcc menu.c -lm -o menu
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值