c#初学者数组

本文关键字:数组 初学者 | 更新日期: 2023-09-27 18:03:03

几个星期前我开始学习c#初学者课程,我在数组上卡住了。我不想要我的问题的完整答案,我想要的工具或链接来解决它自己

我正在尝试制作一个像"气象站"一样的控制台应用程序。程序应该将用户输入作为一个数组,表示已经进行了多少次测量(完成)。之后,用户将在循环中输入度数(Done)

程序应该写出所有的测量值和平均测量值。

我可以计算平均值,但不知道如何打印结果

我已经走了这么远…

   Console.WriteLine("How many measurements have you done");
   string str = Console.ReadLine();
   int size = Convert.ToInt32(str);
   int[] temperatur = new int[size];
   for (int i = 0; i < temperatur.Length; i++)
   {
       Console.WriteLine("Enter temperature " + i + ": ");
       str = Console.ReadLine();
       int element = Convert.ToInt32(str);
       temperatur[i] = element;
   }
   Console.WriteLine("");
   int sum = 0;
  for (int i = 0; i < temperatur.Length; i++)
       sum = sum + temperatur[i];
  Console.WriteLine("The average temperature is " +
                      sum / temperatur.Length);

c#初学者数组

既然你说你唯一的问题是"打印出所有的测量值",你所要做的就是在你已经拥有的for loop上添加一个额外的Console.WriteLine()。您还必须添加大括号。比如:

int sum = 0;
for (int i = 0; i < temperatur.Length; i++){
    sum = sum + temperatur[i];
    Console.WriteLine("Measurement {0} is {1}", i+1, temperatur[i]);
}
Console.WriteLine("The average temperature is " + sum / temperatur.Length);

您可能无法识别Console.WriteLine(),但它基本上是使用占位符格式化输出的一种简洁方式。{0}将被替换为提供的第一个值,{1}将被替换为第二个值。

编辑:Console.WriteLine()String.Format的MSDN文档

    for (int i = 0; i < temperatur.Length; i++)
        sum = sum + temperatur[i]; 
    Console.WriteLine("The average temperature is " + sum / temperatur.Length);

修改为:

    for (int i = 0; i < temperatur.Length; i++)
    {
        sum = sum + temperatur[i]; 
        Console.WriteLine("Temperature {0} is {1}", i, temperatur[i]);
    }
    Console.WriteLine("The average temperature is " + sum / temperatur.Length);

如果你想做同样的事情:

for (int i = 0; i < temperatur.Length; i++) 
{
    sum = sum + temperatur[i];
    Console.WriteLine("Temperature {0}", temperatur[i]);
}
Console.WriteLine("The average temperature is " + sum / temperatur.Length);

在另一个语句中:

for (int i = 0; i < temperatur.Length; i++) 
{
    sum = sum + temperatur[i];
}
temperatur.ForEach(x => Console.WriteLine("Temperature {0}", x));
Console.WriteLine("The average temperature is " + sum / temperatur.Length);
object[] objects = { "hello", 123, true };
for (int i = 0; i < objects.Length; i++)
{
    Console.WriteLine(objects[i].ToString());
}

Console.WriteLine("The average temperature is " + sum / temperatur.Length);
Console.ReadLine();

在结尾键入Console.ReadLine();