我完全被卡住了,所以我会很感激我可以做到这一点的一些指导。
首先,到目前为止,这是我的代码:
int i;
int x = 0;
int b = 0;
Console.Write("\nHow many stocks to enter price for:\t"); // enter size of array
int size = int.Parse(Console.ReadLine());
double[] arr = new double[size]; // size of array
// Accepting value from user
for (i = 0; i < size; i++)
{
Console.Write("\nEnter price for stock #{0}: \t", ++x);
//Storing value in an array
arr[i] = Convert.ToDouble(Console.ReadLine());
}
Console.WriteLine("\n\n");
//Printing the value on console
for (i = 0; i < size; i++)
{
Console.WriteLine("Average Price: " + arr.Average() + " out of {0} stocks", x);
Console.WriteLine("Minimum Price: " + arr.Min());
Console.WriteLine("Number of stocks priced between 1.5-35: " + b);
}
Console.ReadLine();
抱歉,我不太清楚如何添加颜色。
无论如何,我坚持要显示价格在1.5到35之间的股票数量。这一行显示在这一行:Console.WriteLine("Number of stocks priced between 1.5-35: "+ b);
基本上,它要求输入价格的股票数量。这将决定数组的大小。然后,用户将在开头设置它时多次输入股票的价格。因此,计算一只股票的平均价格,然后是最低价格(我坚持的价格),价格在1.5到35之间。
另外,我确信自己可以解决这个问题,但出于某种原因,它每次都会显示2次结果。对此也不太确定。
任何帮助都会受到赞赏,因为我太长时间以来一直坚持这一点。
答案 0 :(得分:1)
你好@Rullcat @Rob建议你必须修复你的最后一个循环。此外,变量b从未被分配,因此您没有定价在1.5和35之间的股票数量。我添加了一个句子来检查
for (i = 0; i < size; i++)
{
//Check if the stock on index i is between 1.5 and 35 and add 1 to the variable b
if(arr[i] >=1.5 && arr[i] <=35.0){
b++
}
}
//Printing the value on console
Console.WriteLine("Average Price: "+ arr.Average() + " out of {0} stocks", x);
Console.WriteLine("Minimum Price: "+ arr.Min());
Console.WriteLine("Number of stocks priced between 1.5-35: "+ b);
Console.ReadLine();
请查看并告诉我您的意见
答案 1 :(得分:1)
提供略短的替代解决方案:
static void Main()
{
int x = 0;
Console.Write("\nHow many stocks to enter price for:\t");
int size = int.Parse(Console.ReadLine());
double[] arr = new double[size];
for (int i = 0; i < size; i++)
{
Console.Write($"\nEnter price for stock #{++x}: \t");
arr[i] = Convert.ToDouble(Console.ReadLine()); //Storing value in an array
}
Console.WriteLine($"\r\nAverage Price: {arr.Average()} out of {arr.Count()} stocks");
Console.WriteLine($"Minimum Price: {arr.Min()}");
Console.WriteLine($"Number of stocks priced between 1.5-35: " +
$"{arr.Where(v => v >= 1.5 && v < 35).Count()}");
Console.ReadLine();
}