2017-02-28 33 views
1
If btnTotalCost.Text = "Calculate total cost" Then 

     btnTotalCost.Text = "Refresh" 
    Else 

     btnTotalCost.Text = "Calculate total cost" 
    End If 

    Dim dHamSandwich As Decimal = 1.35 

    Dim sHamQuantity As Single 

    txtHam.Text = sHamQuantity 

    dTotalSandwichCost = dHamSandwich * sHamQuantity 

    If btnTotalCost.Text = "Refresh" Then 
     MsgBox(dTotalSandwichCost) 


    End If 

当我计算出现的消息框显示数字0.我希望它乘以数量和成本,以给出三明治的总成本。例如,如果我在数量文本框中输入2,则应该将1.35乘以2.乘以单数和小数

+0

dTotalSandwichCost的数据类型是什么?此外,您已将此问题标记为VBA,但我不认为VBA具有Decimal数据类型,并且不允许您在一行中将所有值都设为Dim和set。这可能是VB.Net吗? –

+0

我认为这是我的错误。 –

回答

0

首先,您应该明确指定您使用的是什么。正如Ste Griffiths所说的那样,它似乎是VB.NET。

其次,请开始学习数据类型和变量的用法。

你做

Dim dHamSandwich As Decimal = 1.35 ' <- this is fine 

Dim sHamQuantity As Single '<- this is an uninitialised Single variable, in .net it will be set to 0 

txtHam.Text = sHamQuantity '<- then you assign the unassigned Single variable to your Textbox's property Text(which requires a string) 
'That means it will implicitly convert the Single to String and then "show" it in the textbox (which will be 0) 

dTotalSandwichCost = dHamSandwich * sHamQuantity 'here you multiply 1.35 * 0. Sure it will be 0. Also you multiply a decimal with a single data type which will implicitly convert the latter (if I remember correctly) 

这个问题对我来说这里。为什么你甚至使用Single和Decimal?你可以使用任何一个。但主要问题其实不是数据类型,而是分配。

+0

我使用单打输入三明治数量。文本框中包含单词“数量”。然后我想把它变成一个变量,所以它会变成0.然后我可以输入用户需要的三明治数量。 –

+0

您不能将文本框更改为“变量”。最简单的方法是使用Decimal.TryParse -https://msdn.microsoft.com/de-de/library/system.decimal.tryparse(v = vs.110).aspx与TextHam.Text并将其用于计算。你试图做的就像数据绑定一样。如果您分配txtHam.Text = sHamQuantity,它只会将sHamQuantity的值复制到文本框的文本属性。但是当你改变文本框中的内容时,它不会奇迹般地更新sHamQuantity变量。 – Mono

+0

我如何使用Decimal.TryParse参数与我的txtHam.Text? –