how to calculate average from array in wcf service [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
why it doesn't give me average 3?
public double total = 0;
public double avg = 0;
public double[] Yahoo = { 1, 2, 3, 4,5 };
for (int i = 0; i < Yahoo.Length; i++)
{
total += Yahoo[i];
}
avg = total / Yahoo.Length;

I ran this console application:
class Program
{
static void Main(string[] args)
{
double total = 0;
double avg = 0;
double[] Yahoo = { 1, 2, 3, 4,5 };
for (int i = 0; i < Yahoo.Length; i++)
{
total += Yahoo[i];
}
avg = total / Yahoo.Length;
Console.WriteLine(avg);
Console.ReadKey();
}
}
and I got 3.
However you could use LINQ for that you want:
Yahoo.Average();
Ah, in order to use this method, you have to set this on the top of your source code file the following using statement:
using System.Linq;
Note One thing that seems odd to me, is the way you have declared your variables
public double total = 0;
public double avg = 0;
public double[] Yahoo = { 1, 2, 3, 4,5 };
since those should be declared in a method, they shouldn't have an access modifier. That's wrong.

Related

Have N elemnts of sum of a list and repeat until the end of the list [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm facing a problem when trying to play with C# list. Currently I have a list of integer. And I'm looking for a way to sum up every 5 integer, until the end of the list.
For example I have a list like this:
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
How to sum up every N elements (let's say 5) in the list and become:
[ 15, 40 ]
FYI, the list consist of hundred and thousand int elements.
Thanks.
Since noone's mentioned the simple way yet...
Note that if the input is not divisible by the group size, any extra elements will be ignored. For example, if the input is 11 elements, and the group size is 5, this will give 2 sums of 5 elements and then ignore the 11th input element.
public static int[] SumEvery(int[] input, int groupSize)
{
// The number of groups we have
int numGroups = input.Length / groupSize;
int[] result = new int[numGroups];
// For each group of numbers...
for (int group = 0; group < numGroups; group++)
{
// ... loop through each number in that group, adding to the sum ...
int sum = 0;
for (int i = 0; i < groupSize; i++)
{
sum += input[group * groupSize + i];
}
// ... then store that sum in our array of results
result[group] = sum;
}
return result;
}
int[] input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] result = SumEvery(input, 5);
If you want to stream the results as an IEnumerable<int>, rather than collecting them all into an array, then:
public static IEnumerable<int> SumEvery(int[] input, int groupSize)
{
int numGroups = input.Length / groupSize;
for (int group = 0; group < numGroups; group++)
{
int sum = 0;
for (int i = 0; i < groupSize; i++)
{
sum += input[group * groupSize + i];
}
yield return sum;
}
}
You could do this with a bit of Linq
var ints = new []{1,2,3,4,5,6,7,8,9,10};
var result = ints.Select((x,i) => new{Num = x,Index = i}) // Project to a list with the index and number
.GroupBy (i => i.Index/5) // group by the int division by 5
.Select(g => g.Sum(a => a.Num)); // sum the numbers in each group
Live example: https://dotnetfiddle.net/BabP5N
Note that is is by far the least efficient way - and with a large data set will not perform well. But for a small dataset will work fine. This code is possibly the clearest interpretation of the problem.

C# Creating an Index in a For Loop for an Array [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am attempting to do an assignment and I have attempted to try to record the results of two dice rolls by pulling the possibilities I could get from an array. Basically if I rolled a 2, 4, 5, 5, and 2, I'd record I got two 2s, one 4, and two 5s. However, I am trying to figure out the best way to record it without having to resort to list every single variable 2-12. Might someone be able to assist me in learning how to make the shortcut for this from the code I provide? The code is as follows:
using System;
namespace Assignment
{
class Program
{
static void Main(string[] args)
{
//Initialize variable(s).
int diceRollNum = 0;
//Create the array.
int[] DiceResultArray = new int[11];
//Create the random number.
Random diceRoll = new Random();
//Write out Headers.
Console.WriteLine($"Roll\tCount");
//
for (diceRollNum = 0; diceRollNum < 36000; diceRollNum++)
{
//Roll the dice.
int firstDice = diceRoll.Next(1, 6);
int secondDice = diceRoll.Next(1, 6);
//Add the dice sums.
diceRollNum = firstDice + secondDice;
//Record results.
DiceResultArray[diceRollNum] =
}
//
for (int i = 0; i < DiceResultArray.Length; i++)
{
Console.WriteLine($"{i+2}\t{DiceResultArray[i]}");
}
}
}
}
We are looking for specifically what happens under the Record Results comment. If anyone could help explain this to me, that would be wonderful!
Your code has few issues
diceRollNum is updated in the loop and it runs infinitely.
Random.Next(minValue, maxValue) generates a random value excluding the maxValue. Therefore to get a random number between 1 and 6 we should invoke Next() passing 1 and 7 min and max as parameters respectively
Should reduce 1 from diceRollSum (a new variable which stores the sum of dice values) when accessing the array, as the array is indexed from 0-11, not 1-12
using System;
namespace Assignment
{
class Program
{
static void Main( string[] args )
{
//Initialize variable(s).
int diceRollNum = 0;
//Create the array.
int[] DiceResultArray = new int[12];
//As 1 is not a possible value for the sum of dice values, we can instantiate an array with 11 items and reduce 2 from diceRollSum
//A slightly optimized Approach noted by Andrew
//int[] DiceResultArray = new int[11];
//Creates random instance.
Random diceRoll = new Random();
//Write out Headers.
Console.WriteLine( $"Roll\tCount" );
//
for (diceRollNum = 0; diceRollNum < 36000; diceRollNum++)
{
//Roll the dice.
int firstDice = diceRoll.Next( 1, 7 );
int secondDice = diceRoll.Next( 1, 7 );
//Add the dice sums.
int diceRollSum = firstDice + secondDice;
//Record results.
DiceResultArray[diceRollSum - 1]++;
//Slightly Optimized
//DiceResultArray[diceRollSum - 2]++;
}
//
for (int i = 0; i < DiceResultArray.Length; i++)
{
Console.WriteLine( $"{i+1}\t{DiceResultArray[i]}" );
//Slightly Optimized
//Console.WriteLine( $"{i+2}\t{DiceResultArray[i]}" );
}
}
}
}

Hello, my program jumps over the for loop, and I don't know why [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
using System;
using System.Collections.Generic;
namespace c3
{
class Program
{
static int sumaTotala;
static void Main(string[] args)
{
int teza;
int numberOfNotes;
Console.WriteLine("Numar de note: ");
numberOfNotes = Convert.ToInt32(Console.ReadLine());
List<int> numarDeNote = new List<int>(numberOfNotes);
for (int i = 1; i < numarDeNote.Count + 1; i++)
{
Console.WriteLine("Introdu " + i + " nota: ");
int x = Convert.ToInt32(Console.ReadLine());
numarDeNote.Add(x);
sumaTotala += x;
}
Console.WriteLine("Teza : ");
teza = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Media a rezultat " + NumberInput(numarDeNote, teza, numberOfNotes));
Console.ReadKey();
}
static float NumberInput(List<int> numarNote, int notaTeza, int numarxd)
{
float part1 = sumaTotala / numarxd;
float part2 = part1 * 3;
float part3 = part2 + notaTeza;
float part4 = part3 / 4;
return part4;
}
}
}
The value of numarDeNote.Count starts at 0, and your i starts at 1, so the condition i < numarDeNote.Count + 1 in the for-loop never becomes true. So the loop body is never executed.
Specifying a value when creating the list means that the initial list has room to grow for that many entries, but still initially there are no entries.
That constructor for List just sets the capacity
It still has a Count of zero until you add items
List Constructor (Int32)
Use
for (int i = 1; i < numberOfNotes + 1; i++)
{
Constructor parameter in
List<int> numarDeNote = new List<int>(numberOfNotes);
is Capacity, not Count of the created list.
for (int i = 1; i < numberOfNotes + 1; i++)
{
...

My C# array only sums and averages the last user input [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I built a C# program in which the user is prompted to enter 10 different values and then the program is supposed to sum and average these values and print the sum and average. The problem I am having is that my program is only capturing the last value entered...please help!
namespace ConsoleApplication4
{
class Program
{
const int count = 10;
static void Input(double[] numbers, int num)
{
for (int i = 0; i <= 9; i++)
{
Console.Write("Enter integer {0}: ", i + 1);
numbers[num] = Convert.ToDouble(Console.ReadLine());
}
}
static void Average(double[] numbers, int num)
{
double sum = 0;
double avg = 0;
for (int i = 0; i < numbers.Length; i++)
{
sum += numbers[i];
}
avg = sum / numbers.Length;
Console.WriteLine("The sum of the inputs is {0} and the average is {1}", sum, avg);
}
static void Main(string[] args)
{
double[] numbers = new double[count];
for (int num = 0; num < 1; num++)
{
Input(numbers, num);
Average(numbers, num);
Console.WriteLine("Press the Enter Key");
Console.ReadLine();
}
}
}
}
}
In you Input method, you're assigning user input to numbers[num] instead of numbers[i].
If you look at your Input() method, you're always storing in the num index in your for loop, but num doesn't change in the loop. You should be using numbers[i] instead of numbers[num].
for (int i = 0; i <= 9; i++)
{
Console.Write("Enter integer {0}: ", i + 1);
numbers[num] = Convert.ToDouble(Console.ReadLine());
That should be
numbers[i] = Convert.ToDouble(Console.ReadLine());

Auto Increment the number [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have a problem regarding create squence of number, but i face some problem like given below. I want a number Format Like UK 0000, there are some conditon applied:
It start from UK 0001
After reaches 9 record then 10th record is like UK 0010
If all digit fill Like UK 9999 then next record show like UK 10000 and so on
Please help me for this, It can use any platform like
jquery
c#
sql etc...
in c#, you can do this
string s = "UK";
int counter = 0;
if (counter < 10000)
result = s + counter++.ToString().PadLeft(4, '0');
else
result = s + counter++.ToString();
Output: UK0000,UK0001,UK0002......
IEnumerable<int> numbers= Enumerable.Range(1, 10000).Select(x=>x);
var list = squares.Select(numbers => "UK" + numbers.ToString("0000")).ToList();
try
List<string> lista = new List<string>();
for (int num = 0; num < 12000; num++)
{
lista.Add(string.Format("UK {0}", num > 999 ? num.ToString() : num.ToString().PadLeft(4, '0')));
}
USING JQUERY - Here is a working example : jsfiddle
Jquery :
$(document).ready(function () {
var prefix = "UK";
var max = 4;
var limit = 10004;
for (var i = 0; i < limit - 1; i++) {
var a = prefix + pad(i, max);
$("#msg").append(a);
$("#msg").append("<br/>");
}
function pad(str, max) {
str = str.toString();
return str.length < max ? pad("0" + str, max) : str;
}
});

Categories