我需要一个简单的任务帮助:
输入整数 n 并输出总和:1 + 2 ^ 2 + 3 ^ 2 + ... + n ^ 2。使用 n 的输入验证为正。 我的代码不起作用,直到现在:
Sub Main()
Dim inputNumber As Integer
Console.WriteLine("Please enter a positive number.")
inputNumber = Console.ReadLine()
If inputNumber <= 0 Then
Console.WriteLine("Please use only positive numbers > 0 !")
End If
Dim sum As Integer
Dim i As Integer = 1
For i = 1 To i <= inputNumber
sum = sum + (i * i)
i = i + 1
Next
Console.WriteLine(sum)
Console.ReadLine()
End Sub
答案 0 :(得分:2)
尝试以下更改:
Dim inputNumber as Long ' not Integer. Also change sum, i.
...
inputNumber = CLng(Console.ReadLine) ' make it a number, not a string
...
Dim sum as Long ' yum
dim i as Long ' don't assign it here
for i = 1 to inputNumber ' don't use "<=" in a for loop
...
' i = i+1 ' Don't increment i within the loop, since the loop does that for you.