本文介绍了C#如何获取文本框中数字的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如在文本框中我写了1020,当我点击爆炸按钮时,它会在文本框中显示3,因为1 + 0 + 2 + 0 = 3.
我尝试过的事情:
我已经厌倦了这样的事情`
For example in textbox i have written 1020,when i will click on Explode button, it will show 3 in textbox, because 1+0+2+0=3.
What I have tried:
I have tired like this`
int total = 0;
total = int.Parse(button1.Text) + int.Parse(button2.Text) + int.Parse(button3.Text) + int.Parse(button4.Text) + int.Parse(button5.Text) + int.Parse(button6.Text) + int.Parse(button7.Text) + int.Parse(button8.Text) + int.Parse(button9.Text) + int.Parse(button11.Text);
textbox.Text = total.ToString();
但在这种情况下,当我点击爆炸按钮时,它总是显示45`因为1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45。
如何编写此代码,以便显示我输入数字的总和?
But in this case when i click on Explode button it always show 45` because 1+2+3+4+5+6+7+8+9=45.
How can i write this code, in order it show me sum of my input numbers?
推荐答案
int total = 0;
foreach (char ch in this.textBox1.Text)
{
total += int.Parse(ch.ToString());
}
this.textBox1.Text = total.ToString();
string mytext = "1020";
int sumOfChars = mytext.Sum(x=>Convert.ToInt32(x.ToString())); //3
int num = "1020".Sum(n => n & 15);
int sum = (int)"1020".Sum(n => Char.GetNumericValue(n));
注意:'GetNumericValue返回一个double,我发现那很奇怪。
Note: 'GetNumericValue returns a double, and I find that strange.
这篇关于C#如何获取文本框中数字的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!