2017-07-04 17 views
0

,我有這個想法是:C#我怎樣才能使之王氏到Console.ReadLine

  • 設置一些變量,其號碼,如int a=15, b=10, c=1
  • 然後使用Console.Readline能夠做到的總和,例如在控制檯上寫的+ a + b必須顯示40.

我試過Console.WriteLine("sum: {0}",Console.Readline());我可以上傳一個圖片的想法,如果這不足以對我的英語感到抱歉。

+0

你的英語很好,但它會幫助如果你清理了你的文章並對代碼進行了格式化,所以它更易於閱讀。另外,請考慮使用「字典」。另外,你已經嘗試過的代碼有什麼問題......是否做了一些意想不到的事情,顯示錯誤,拋出異常? –

+0

歡迎來到SO!請在此閱讀並格式化您的問題: https://stackoverflow.com/help/how-to-answer – garfbradaz

+0

您可能需要查看[Reverse Polish notation](https://en.wikipedia.org/wiki)/Reverse_Polish_notation)和[Shunting-yard算法](https://en.wikipedia.org/wiki/Shunting-yard_algorithm)以及@GrantWinney推薦的'Dictionary' – petelids

回答

2
int sum = 0; 
var values = new Dictionary<string, int> 
{ 
    { "a", 1 }, 
    { "b", 2 }, 
    { "c", 3 } 
}; 
var input = Console.ReadLine().Split('+'); 
foreach (string variable in input) 
{ 
    sum += values.ContainsKey(variable) ? values[variable] : 0; 
} 
Console.WriteLine("Sum: {0}", sum); 

例如:

a+b+c 
Sum: 6 
+0

令人驚歎的,就像你的其他代碼:D謝謝,它是這樣的,但不是把值放在字母上,它會更像: Console.ReadLine(); 然後我介紹一下,a + b + c 結果會給我16,如果我想把+ a + a + a那麼結果就是4.基本上我想和我的變量的值相加。 –

+0

好的,我看到了..... – derloopkat

+0

我編輯了我的解決方案 – derloopkat

-1

基本過程,如果你只是想添加:拆分輸入字符串,然後迭代通過所述輸出,同時將所有的數字相加。輸出將以字符串格式輸出,因此必須提供投射。

全碼:

string[] tmp_out = Console.ReadLine().Split('+'); 
int tmp_sum = 0; 
foreach (string tmp_number in tmp_out) 
{ 
    tmp_sum += int.Parse(tmp_number); // consider using TryParse if you are not sure if the input format is correct 
} 
Console.WriteLine("Sum=" + tmp_sum); 

如果您需要進一步的計算能力,看看CSharpCorner

+0

非常感謝:D您的代碼幫助我瞭解了更多這方面的知識! –