2013-03-15 89 views
1

我有以下代碼:不能圍捕了一些

Dim a as Long 
a = InputBox("a=") 
Dim nr_cifre as Long 
nr_cifre = 0 
Dim n as Long 
n=a 
Do While n <> 0 
    n=n/10 
    nr_cifre = nr_cifre + 1 
Loop 
If a - a mod (10 * nr_cifre) = 0.5 Then 
    a=a+0.9+(nr_cifre*10) 
End If 
MsgBox a mod (10 * nr_cifre) 

基本上,它試圖圍捕號碼。因此,2.3將變爲2.另外,它試圖收集,例如2.5到3.

該示例適用於小數字,如1234,5。但如果我試圖收集12345,6,它會給我一些奇怪的錯誤。我也嘗試過VB6中的代碼,但沒有成功。

我可以問你的幫助/建議嗎?任何提示高度讚賞。提前致謝!

+0

你有什麼反對Round - 'round(2.6,0)'?無可否認,它讓銀行家四捨五入,但這似乎是你想要的。另見http://blogs.msdn.com/b/ericlippert/archive/2003/09/26/bankers-rounding.aspx – Fionnuala 2013-03-15 22:52:56

+2

「給我一些奇怪的錯誤」對任何人都沒有意義,除了你,因爲我們看不到你的屏幕或閱讀你的想法。如果您遇到錯誤,請提供您正在收到的確切錯誤**或您遇到的問題,包括您收到的任何錯誤消息。 (你可以使用'Round'(或'Ceiling',如果你總想收起來;它可能是VBScript中的Ceil'--我不記得了),其中任何一種都比試圖寫自己的更好。) – 2013-03-15 22:53:24

+0

@Remou這次我必須自己制定一個算法,所以我不能使用編程語言的嵌入式函數。 – 2013-03-15 22:57:34

回答

3

如果你需要那麼你自己的算法試試這個:

WSH.Echo CustomRound(-123456.7) '-123457 
WSH.Echo CustomRound(-123456.5) '-123456 
WSH.Echo CustomRound(-123456.3) '-123456 
WSH.Echo CustomRound(123456.7) '123457 
WSH.Echo CustomRound(123456.5) '123457 
WSH.Echo CustomRound(123456.3) '123456 

Function CustomRound(nValue) 
    CustomRound = Int(nValue + 0.5) 
End Function 

或...

WSH.Echo CustomRound2(-123456.7) '-123457 
WSH.Echo CustomRound2(-123456.5) '-123457 
WSH.Echo CustomRound2(-123456.3) '-123456 
WSH.Echo CustomRound2(123456.7) '123457 
WSH.Echo CustomRound2(123456.5) '123457 
WSH.Echo CustomRound2(123456.3) '123456 

Function CustomRound2(nValue) 
    CustomRound2 = Sgn(nValue) * Int(Abs(nValue) + 0.5) 
End Function 

嗯......多一個想法:)

Function RoundFrm(nValue) 
    RoundFrm = Null 
    If IsEmpty(nValue) Or _ 
    Not IsNumeric(nValue) Then Exit Function 
    RoundFrm = FormatNumber(nValue, 0) 
End Function 

而且使用以上的想法可以使功能更完整...

Function RoundEx(nValue) 
    Select Case VarType(nValue) 
     Case vbInteger, vbLong 
      RoundEx = nValue 
     Case vbSingle 
      RoundEx = CSng(FormatNumber(nValue, 0)) 
     Case vbDouble 
      RoundEx = CDbl(FormatNumber(nValue, 0)) 
     Case vbCurrency 
      RoundEx = CCur(FormatNumber(nValue, 0)) 
     Case Else: RoundEx = Null 
    End Select 
End Function 
+0

我在上面的代碼中嘗試過類似的東西,但是我沒有使用Int函數,而是使用了相同的結果。事實上,我認爲錯誤是由數字計數循環產生的... – 2013-03-15 23:24:26

+0

我用一個更多的功能更新我的答案。我將這兩個概念都用在沒有內置Round函數的語言中(只有Ceil/Floor),我認爲它已被證明。 – 2013-03-15 23:39:00