2014-12-26 59 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變量未包含在靜態主要方法中捕獲的值。這些方法只是局部變量

相關問題