2014-12-26 57 views
-5

我试图做一个函数的计算器,但是当我想返回我的值的'计算',它会给我的函数中变量的值是0而不是计算。 当我编写正确的操作符时,也会显示默认文本。c#控制台应用程序简单的计算器不工作

static void Main(string[] args) 
    { 

     string input1,input2,opera,product = ""; 
     Int32 v,n; 

     Console.WriteLine("please insert first number: "); 
     input1 = Console.ReadLine(); 

     Console.WriteLine("please insert second number: "); 
     input2 = Console.ReadLine(); 

     if (numeric(input1, out v) && numeric(input2, out n)) 
     { 
      Console.WriteLine("give operator: *, /, -, +"); 
      opera = Console.ReadLine(); 

      Console.WriteLine(operat(product)); 


     } 

    private static string operat(string oper){ 

     double input1 = 0, input2 = 0; 
     double calculation = 0; 

     switch (oper) 
     { 
      case "*": 
       calculation += input1 * input2; 
       break; 
      case "/": 
       calculation += input1/input2; 
       break; 
      case "+": 
       calculation += input1 + input2; 
       break; ; 
      case "-": 
       calculation += input1 - input2; 
       return calculation.ToString(); 
      default: 
       Console.WriteLine("you gave the write operator..."); 
       break; 
     } 
     return calculation.ToString(); 

忽略的数值函数...

+0

当调用'operat'您正在使用'product'变量,它似乎没有设置。 –

+0

哈哈!试想一下......提示:0次0等于什么? –

+3

看起来像是一个用调试器练习的好机会。逐步浏览代码,在每一步检查每个变量的值。当你指出某个变量的值不是预期的值时,找出原因并解决该问题。冲洗,重复。 –

回答

1

更改OPERAT功能

private static string operat(string oper,double input1,double input2) 

,并删除此行

double input1 = 0, input2 = 0; 

并调用OPERAT功能

operat(opera,double.Parse(input1),double.Parse(input2)); 
+0

你几乎拥有它......你确定你传递了正确的参数吗? – Rolo

+0

我想出了你的帮助,谢谢你花时间。 – Thibaut

+1

@xwpedram指出了这个问题的第一条评论,你应该通过歌剧而不是产品。 – Rolo

2

仅仅因为你的名字你变量不同的功能(input1input2)相同,但这并不意味着他们将有相同的价值观。事实上,他们甚至没有相同的类型!尝试删除=0部分以查看它,编译器会告诉你它从未分配给它。

你想要的只是在主函数中保存操作数和操作符的变量,并将它们传递给你的工作函数。

0

将静态void main中的input1和input2重构为class字段。在操作方法中使用这些参考。运算符方法中的input1和input2变量未包含在静态主要方法中捕获的值。这些方法只是局部变量

相关问题