2012-11-23 15 views
0

大家好:我在VB.Net很綠,而且我很難理解轉換數字的邏輯,然後將該數字轉換爲等於該數字的字符串。顯示數字,轉換數字,然後顯示結果作爲特殊字符的數量VB.Net

例子:

 
    Input = 1; Output as string using * is: * (4 asterisks, and etc.) 
    Input = 3; Output as string using # is: ### (and so on).

教授給我們佈置任務,從用戶獲得銷售金額,然後顯示與信息類型條形圖。 * = $ 100。因此,600美元將等於**。我可以得到這些信息,但是我迷失在如何轉換它。希望我明確表達這個問題!下面是我在做什麼......已經是得到了循環獲取信息:

' The variables 
    Dim dblValueA, dblSales, dblTotal As Double 
    Dim dblValueB As Double = 1 
    Dim strInput, strChgVal As String 
    Dim strSymbol As String = "*" 
    Dim strOutput As String 
    ' get some input via a loop structure: 
    Try 


    For intCount As Integer = 1 to 5 ' Sales/Input for 5 Stores 
    strInput = InputBox("place input here:") 
     dblSales = CInt(strInput) 
      dblTotal = dblSales 
      dblValueA = (dblTotal/dblValueB) 
      strChgVal = Cstr(dblValueA) 
      strOutput = strChgVal 
      strSymbol = strOutput 

      lstOutput.Items.Add(dblValueA.ToString) 

    Next 
    Catch ex As Exception 

    End Try 

它的工作原理,我只是失去了對如何使我的輸出顯示輸入的實際數量。如何做到這一點?

+0

我覺得我沒有得到這個問題。如果'*'= $ 100,那麼$ 600 ='******'(6星)而不是'**'(2星)。 – Neolisk

回答

0

我真的很喜歡使用字符串構造函數重載,如@David's answer建議。然而,按照我的意見有我想補充這樣的代碼:

Public Function ToTextBars(ByVal input As Decimal, ByVal marginalValue As Decimal, ByVal BarCharacter As Char) As String 
    'Always use a Decimal, not Double or Integer, when working with money 

    Return New String(BarCharacter, CInt(CDec(dblValueA)/marginalValue)) 
End Function 

它仍然是一個班輪:)然後調用它像這樣:

Console.WriteLine(ToTextBars(600d, 100d, "*"c)) 

或像這樣:

Dim result As String = ToTextBars(3d, 1d, "#"c) 

而結果將是:

******

但是,我懷疑在這裏寫一個循環是作業目標的一部分。使用字符串重載會錯過這一點。在這種情況下,我會這樣寫:

Public Function ToTextBars(ByVal input As Decimal, ByVal marginalValue As Decimal, ByVal BarCharacter As Char) As String 
    If input < 0 Then input *= -1 
    Dim charCount As Integer = 0 

    While input > 0 
     charCount += 1 
     input -= marginalValue    
    End While 

    Return New String(BarCharacter, charCount) 
End While 

您將以與第一個相同的方式調用此函數。這仍然使用字符串構造函數重載,但它不能避免我希望教授希望你編寫的循環。

這裏還有一個風格點。你在哪裏拿起strdbl前綴習慣?你的教授教你這個嗎?這在vb6的日子裏很流行,它是.Net之前的預定義者。現在,這不再被認爲是有幫助的,而且微軟自己的風格指南特別推薦使用這些前綴。將您的教授這個鏈接,如果他不相信你:

http://msdn.microsoft.com/en-us/library/ms229045.aspx

1

像這樣:

strSymbol = New String("*"c, CInt(dblValueA)) 
+0

我會爲該表達式添加一個'marginalValue'變量和一個'/ marginalValue',對於每個$ 100都值一個*的問題,600美元就像******。否則,這是完美的,+1 –

+0

是的。我在這裏假設'dblValueB'正在填補這個目的,但是更確切地說,更明確更好。 – prprcupofcoffee

相關問題