I'm new to coding here.
I am trying to use coding to show statistic for Average, Maximum and Minimum.
I have the error there they say I cannot convert decimal[] to int[]. I have commented the error below beside my code. It is one of the last few lines.
I'm required to use Arrays for this project and the values must be in decimal.
Thank you and sorry if I am doing something wrong, I am new.
namespace Group_Project_Final
{
public partial class LoanRates : Form
{
public LoanRates()
{
InitializeComponent();
}
private double Average (int [] iArray)
{
int total = 0;
double average;
for(int index=0;index<iArray.Length;index++)
{
total += iArray[index];
}
average = (double)total / iArray.Length;
return average;
}
private decimal Highest (int [] iArray)
{
int highest = iArray[0];
for (int index =1; index<iArray.Length;index++)
{
if(iArray[index]>highest)
{
highest = iArray[index];
}
}
return highest;
}
private decimal Lowest(int [] iArray)
{
int lowest = iArray[0];
for (int index =1; index<iArray.Length; index++)
{
if(iArray[index]<lowest)
{
lowest = iArray[index];
}
}
return lowest;
}
private void button6_Click(object sender, EventArgs e)
{
Home form1 = new Home();
form1.Show();
}
private void button7_Click(object sender, EventArgs e)
{
decimal [] rates = { 1.60m, 1.65m ,1.62m, 1.55m, 1.68m, 1.58m };
int index = 0;
decimal highestRate;
decimal lowestRate;
double averageRate;
while(index<rates.Length)
{
decimal.ToInt32(rates[index]);
index++;
}
highestRate = Highest(rates); //i am having the error here where they say "cannot simply convert decimal[] to int[]
lowestRate = Lowest(rates);
averageRate = Average(rates);
txtAvg.Text = averageRate.ToString();
txtHighest.Text = highestRate.ToString();
txtLowest.Text = lowestRate.ToString();
}
}
}
Highestneeds anint[]butratesis adecimal[]. In addition, unless this is for learning purposes then use linq'sMin,MaxandAveragemethods.Average(int [] iArray)toAverage(decimal [] dArray). All your logic is fine, the only issue is that you are trying to convert between decimal[] and integer[].iArray). That's commonly called Hungarian Notation, and is widely considered a bad practice. In C# you explicitly have to declare the type of the parameter (int[]), so including the type as a prefix of the name is redundant. It also means you have to rename variables if you change their type (e.g. in my previous comment), and it is generally a pain to work with.Averagemethod return adouble, but the others return adecimal? I'd make them all returndecimalfor consistency and because your source values aredecimals. Also note that if you did successfully convert the values toInt32that you lose the fractional part of each number.. Is that what you intend? All your method would return1.0in that case becauseToInt32simply truncates the decimal.