小菜编程成长记(二 代码规范、重构)

(续上篇) 
        大鸟说:“且先不说出题人的意思,单就你现在的代码,就有很多不足的地方需要改进。比如变量命名,你的命名就是ABCD,变量不带有任何具体含义,这是非常不规范的;判断分支,你这样的写法,意味着每个条件都要做判断,等于计算机做了三次无用功;数据输入有效性判断等,如果用户输入的是字符符号而不是数字怎么办?如果除数时,客户输入了0怎么办?这些都是可以改进的地方。”
  “哦,说得没错,这个我以前听老师说过,可是从来没有在意过,我马上改,改完再给你看看。”

 

None.gif class  Program
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
static void Main(string[] args)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
try
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Console.Write(
"请输入数字A:");
InBlock.gif            
string strNumberA = Console.ReadLine();
InBlock.gif            Console.Write(
"请选择运算符号(+、-、*、/):");
InBlock.gif            
string strOperate = Console.ReadLine();
InBlock.gif            Console.Write(
"请输入数字B:");
InBlock.gif            
string strNumberB = Console.ReadLine();
InBlock.gif            
string strResult = "";
InBlock.gif
InBlock.gif            
switch (strOperate)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
case "+":
InBlock.gif                    strResult 
= Convert.ToString(Convert.ToDouble(strNumberA) + Convert.ToDouble(strNumberB));
InBlock.gif                    
break;
InBlock.gif                
case "-":
InBlock.gif                    strResult 
= Convert.ToString(Convert.ToDouble(strNumberA) - Convert.ToDouble(strNumberB));
InBlock.gif                    
break;
InBlock.gif                
case "*":
InBlock.gif                    strResult 
= Convert.ToString(Convert.ToDouble(strNumberA) * Convert.ToDouble(strNumberB));
InBlock.gif                    
break;
InBlock.gif                
case "/":
InBlock.gif                    
if (strNumberB != "0")
InBlock.gif                        strResult 
= Convert.ToString(Convert.ToDouble(strNumberA) / Convert.ToDouble(strNumberB));
InBlock.gif                    
else
InBlock.gif                        strResult 
= "除数不能为0";
InBlock.gif                    
break;
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            Console.WriteLine(
"结果是:" + strResult);
InBlock.gif            
InBlock.gif            Console.ReadLine();
InBlock.gif
InBlock.gif
ExpandedSubBlockEnd.gif        }

InBlock.gif        
catch (Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Console.WriteLine(
"您的输入有错:" + ex.Message);
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}


        大鸟:“吼吼,不错,不错,改得很快吗?至在目前代码来说,实现计算器是没有问题了,但这样写出的代码是否合出题人的意思呢?”
        小菜:“你的意思是面向对象?”
        大鸟:“哈,小菜非小菜也!”

(待续)


      

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值