I have a problem to find the average of numbers string input by user in c#. Please help me on [email protected]
Example:- 0124 =7/4=1.75
Thanks in advance
Anand Vikram
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Sibeesh VenuRank #27 · 42.9K reputationPosted Dec 23, 2014, 2:49 AM EST
Please note that I have not tested this code.
using System;
class Program
{
static void Main()
{
int sum,avg;
const string s = "0124";
foreach (char c in s)
{
sum=sum+convert.toint32(c);
}
avg=(sum)/(s.Length)
}
}
VulpesRank #55 · 29.2K reputationPosted Dec 23, 2014, 3:07 AM EST
Note that, to avoid the use of integer arithmetic when calculating the average, you need to cast at least one of the operands to double:
Vikram AgrawalRank #4,713 · 329 reputationPosted Dec 23, 2014, 3:13 AM EST
Sibeesh already written the solution for your problem but some small mistakes are there.
You can try this one also.
Here i have written One Function which will return you the average of the number in the string.
public double Average(string str)
{
int sum=0,len;
len=str.Length;
for(int i=0;i
{
sum=sum+Convert.ToInt32(str[i]);
}
return sum / len ;
}