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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Vikram AgrawalPosted Dec 23, 2014, 8:13 AM
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 ;
}
VulpesPosted Dec 23, 2014, 8:07 AM
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:
Sibeesh VenuPosted Dec 23, 2014, 7:49 AM
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)
}
}