Mrinaal
Mrinaal

Reputation: 7

Sum of digits program, Getting wrong answer

I have used querystring to accept number in my classic asp code, and then the program will output the sum of digits of the number.

<%
dim n,d,sum
sum = 0
d = 0
n = request.querystring("n")  //Taking value from querystring
while n<>0
d = n mod 10
response.write("<br>"&d)
sum = sum + d``
n = Cint(n/10)
wend
response.write("<br>Sum of digits of "&request.querystring("n")&" is : 
"&sum)
%>

But the problem is it does not show correct answers for few values like for eg. n=91....then output will be 11 but for n=123...the output will be 6. pls help.

Upvotes: 1

Views: 542

Answers (2)

Mrinaal
Mrinaal

Reputation: 7

Only have to do one change in the code , i.e. use the operator \ instead of / when you reduce your number....

i.e. instead of n = CInt(n/10) use n = n\10

Therefore the code will work fine as butter:

<%
dim n,sum,d
sum = 0
n = request.querystring("n")    'taking value from querystring

while n <> 0
d = n mod 10
sum = sum +d
n = n\10                       'using \ for integer division
wend
response.write("Sum of digits of : "&request.querystring("n")&" is = "&sum)
%>

For those who dont understand what just happened see below:

  1. Operator / : Performs a floating division.
  2. Operator \ : Performs a Integer division.

Thats why I was not getting correct results. Hope this helps!

Upvotes: 0

ThatGuyInIT
ThatGuyInIT

Reputation: 2239

It might be easier to treat n as a string, which is really a character array. Because a string is a character array we can loop through the array and sum each value.

Dim n, d, sum
sum = 0
d = 0
n = Request.QueryString("n")
If IsNumeric(n) Then
    For i = 1 To Len(n)
        d = CInt(Mid(n,i,1))
        Response.Write("<br />" & d)
        sum = sum + d
    Next
    Response.Write("<br />Sum of digits of " & n & " is : " & sum)
End If

Upvotes: 1

Related Questions