关于switch语句的简化问题?

thinkxl 2005-02-19 09:54:26
有这样一道题,从键盘输入一个值,这个值有100种情况,程序跟随据不同的选择进行不同的执行,请问如何想?我想到的是用switch语句,可是如果这样写那就要写100个case语句,感觉太多了,有没有什么办法,能写的少一点?用c语言写。下面是我用switch语句写的。
main()
{ int i;
scanf("%d",&i);
switch(i)
{ case 1:
case 2:
.
.
case 99:
case 100:
}
}
...全文
240 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
bing_huo 2005-02-19
  • 打赏
  • 举报
回复
如果所谓的操作需要的参数表和返回值不同意 指针数组还是不行。。。。。。
sloriver 2005-02-19
  • 打赏
  • 举报
回复
100种情况,需要100哥判断,很符合自然规律啊
pcboyxhy 2005-02-19
  • 打赏
  • 举报
回复
函数指针数组。
参考这个吧

#include <iostream>
#include <cstdlib>

using namespace std;

const int size=100;

struct Goods
{
char name[20];
double cost;
double sellprice;
int on_hand;
static int index;
} good[size];

int Goods::index = 0;

int GetCmd( );
int Enter( );
int Play( );
int Search( );
int Quit( );

int main(int argc, char *argv[])
{
int (*fun[ ])( )={Enter, Play, Search, Quit};
while(1)
fun[GetCmd()] ( );
return 0;
}

int GetCmd( )
{
system("CLS");
int ch;
cout<<"(0)Enter\n(1)Play\n(2)Search\n(3)Quit\nplease choose one:";
while(1)
{
cin>>ch;
if(ch<0 || ch>3)
cout<<"输入错误."<<endl;
else
break;
}
system("CLS");
return ch;
}

int Enter( )
{
int index = Goods::index;
if(index == size)
{
cout<<"空间已满,不能再输入数据!";
return 0;
}
cout<<"请输入数据"<<endl;
cout<<"货物名称:"; cin>>good[index].name;
cout<<"进价:"; cin>>good[index].cost;
cout<<"售价:"; cin>>good[index].sellprice;
cout<<"库存量:"; cin>>good[index].on_hand;
Goods::index = index + 1;
}

int Play( )
{
int index = Goods::index;
for(int i=0; i<index; ++i)
{
cout<<"货物名称: "<<good[i].name<<endl;
cout<<"货物进价: "<<good[i].cost<<endl;
cout<<"货物售价: "<<good[i].sellprice<<endl;
cout<<"货物库存: "<<good[i].on_hand<<endl<<endl;
}
system("PAUSE");
}

int Search( )
{
int index = Goods::index, i;
char name[20];
cout<<"输入查询的货物名称";
cin>>name;
for(i=0; i<index; ++i)
if(strcmp(name, good[i].name)==0)
break;
if(i==index)
cout<<endl<<"没有找到"<<endl;
else
{
system("CLS");
cout<<"货物名称: "<<good[i].name<<endl;
cout<<"货物进价: "<<good[i].cost<<endl;
cout<<"货物售价: "<<good[i].sellprice<<endl;
cout<<"货物库存: "<<good[i].on_hand<<endl;
}
system("PAUSE");
}

int Quit( )
{
exit(0);
}
EnochShen 2005-02-19
  • 打赏
  • 举报
回复
通常我都是将Switch语句中根据发生频率来进行case排序,将大的switch语句转为嵌套switch语句,多少可以提高一下速度,简化。。。如果都是没有规律的,没办法
bing_huo 2005-02-19
  • 打赏
  • 举报
回复
把操作写成函数 写个表 包括值和函数指针 。。。。。然后查表调函数。。。

好象更麻烦了。。@_@
bing_huo 2005-02-19
  • 打赏
  • 举报
回复
gz
fangyingjf 2005-02-19
  • 打赏
  • 举报
回复
就这么写吧
如果你能把这些输入值归类一下再做,那自然是再好不过了
wuzhihong 2005-02-19
  • 打赏
  • 举报
回复
如果100种情况各不相同,我觉得好像没办法简化吧
tttx 2005-02-19
  • 打赏
  • 举报
回复
case后面的代码是不是都差不多,如果不是那写100也是没办法的事了。。。

69,369

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧