c#在添加时遇到问题
我是新手,所以请耐心等待,我现在在添加方面有点麻烦。我试图让它,所以每次你点击按钮,它增加了5到总数。有人能帮我吗 这是班级现金箱:c#在添加时遇到问题,c#,addition,C#,Addition,我是新手,所以请耐心等待,我现在在添加方面有点麻烦。我试图让它,所以每次你点击按钮,它增加了5到总数。有人能帮我吗 这是班级现金箱: public string cash1() { return "5"; } 这是单击按钮时的代码: CashBox fivepence; fivepence = new CashBox(); txtMoney.Text = txtMoney.Text + fivepence.cash1(); total1 = total1 + double.Parse(t
public string cash1()
{
return "5";
}
这是单击按钮时的代码:
CashBox fivepence;
fivepence = new CashBox();
txtMoney.Text = txtMoney.Text + fivepence.cash1();
total1 = total1 + double.Parse(txtMoney.Text);
如果按下按钮三次,结果是555而不是15。
任何帮助都将不胜感激 您需要返回整数
5
,而不是字符串。当前方法将返回字符串,结果将是字符串串联而不是整数相加。尝试:
public int cash1()
{
return 5;
}
然后:
txtMoney.Text = (double.Parse(txtMoney.Text) + fivepence.cash1()).ToString();
total1 = total1 + double.Parse(txtMoney.Text); //or total1 += double.Parse(txtMoney.Text);
您应该按照相反的顺序进行操作:首先进行添加,然后使用结果更新UI。首先,将
cash1
更改为return5
(整数,而不是字符串)。然后:
无论什么时候你要问一个问题,一定要写下你的问题是什么。真的吗?我们有“添加”标签吗?有人特别对涉及数字相加的问题感兴趣?
“5”+“5”=“55”
您应该使用十进制而不是字符串。那么,在将字符串赋给Text
属性之前,他是否应该将该值转换为字符串?@Bartdude,不太确定,但是我添加了它,您不能将表达式强制转换为字符串
,因为它是双精度
。而是使用.ToString()
。这就是(double.Parse(txtMoney.Text)+5便士.cash1()).ToString()
。
// do the math
var subtotal = double.Parse(txtMoney.Text) + fivepence.cash1();
// update the user interface
txtMoney.Text = subtotal.ToString();
// update total1, whatever that is
total1 += subtotal;