VB程序产生不正确的输出

时间:2014-02-02 16:02:19

标签: vb.net visual-studio-2010 function

Function ScoreAverage(ByVal Sname As String, ByVal test1 As Integer, ByVal test2 As Integer, ByVal test3 As Integer)
    Dim average As Integer

    average = (test1 + test2 + test3) / 3

    If average > 7 Then
        Console.WriteLine(Sname & " your average score is " & average & " which is excellent")
    ElseIf average > 4 <= 7 Then
        Console.WriteLine(Sname & "  your average score is " & average & " which is good")
    ElseIf average <= 4 Then
        Console.WriteLine(Sname & "  your average score is " & average & " which is a fail")
    End If

    ScoreAverage = average
End Function
Sub Main()
    Dim Sname As String
    Dim test1, test2, test3 As Integer

    Console.WriteLine("This programme calculates the average of 3 tests scored out of 10")
    Console.WriteLine("Please enter your name...")
    Sname = Console.ReadLine

    Console.WriteLine(Sname & " enter your first test score out of 10")
    test1 = Console.ReadLine

    Console.WriteLine(Sname & " enter your second test score out of 10")
    test2 = Console.ReadLine

    Console.WriteLine(Sname & " enter your second test score out of 10")
    test3 = Console.ReadLine


    ScoreAverage(Sname, test1, test2, test3)

End Sub

结束模块

我使用vb上的函数编写了这个程序,但是当我运行它时,我的平均输出不正确。谁能帮助弄清楚我做错了什么或错过了什么?感谢。

2 个答案:

答案 0 :(得分:1)

将您的代码更改为:

Dim average As Double = ((test1 + test2 + test3) / 3)

并将输出更改为:

If average > 7 Then
    Console.WriteLine(Sname & " your average score is " & average.ToString("N2") & " which is excellent")
ElseIf average <= 4 Then
    Console.WriteLine(Sname & "  your average score is " & average.ToString("N2") & " which is a fail")
Else
    Console.WriteLine(Sname & "  your average score is " & average.ToString("N2") & " which is good")
End If

答案 1 :(得分:1)

更改

average = test1 + test2 + test3 /3

average = (test1 + test2 + test3) /3 

您正在添加test1和test2,然后添加1/3的test3,括号将允许您添加测试结果,然后将它们除以3.请参阅MSDN article on Operator Precedence

你还要从ScoreAverage函数中返回一个整数,你需要返回一个Double,因为它现在就可以得到整数。

Function ScoreAverage(ByVal Sname As String, ByVal test1 As Integer, ByVal test2 As Integer, ByVal test3 As Integer) As Double
    Dim average As Double

    average = (test1 + test2 + test3) / 3

    If average > 7 Then
        Console.WriteLine(Sname & " your average score is " & average.ToString("N2") & " which is excellent")
    ElseIf average > 4 Then
        Console.WriteLine(Sname & "  your average score is " & average.ToString("N2") & " which is good")
    Else
        Console.WriteLine(Sname & "  your average score is " & average.ToString("N2") & " which is a fail")
    End If

    Return average
End Function