c# – 如何排除数组的值?

前端之家收集整理的这篇文章主要介绍了c# – 如何排除数组的值?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何创建排除最低温度并计算平均温度的方法.我只想要一个提示,而不是完整的解决方案,因为我想自己解决我的编程问题.我只有大约10个班级…评论人们的评论我的教授没有讲课,我读过我的书多次回顾过它.

我让这个程序从用户那里拿一个号码.该数字将添加到数组中.该数组用于创建类Temp的实例以打印最低和最高临时值.

  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. Console.Write("Enter a Temperature in Degrees:");
  6. string n = Console.ReadLine();
  7. int number = Convert.ToInt32( n);
  8. Temp t = new Temp(100,52,98,30,11,54,number);
  9. Console.WriteLine("Lowest Temperature:{0}",t.lowest());
  10. Console.WriteLine("Highest Temperature: {0}",t.highest());
  11. Console.WriteLine("Average Temperature: {0}",t.Average());
  12. }
  13.  
  14. public class Temp
  15. {
  16. private int[] temp = new int[7]; // array
  17. public Temp(int d1,int d2,int d3,int d4,int d5,int d6,int d7) // constructor with 7 parameters
  18. {
  19. temp[0] = d1; // assigning constructor parameters to array
  20. temp[1] = d2;
  21. temp[2] = d3;
  22. temp[3] = d4;
  23. temp[4] = d5;
  24. temp[5] = d6;
  25. temp[6] = d7;
  26. }
  27.  
  28. public int lowest() // returning the lowest value of the set of numbers
  29. {
  30. int smallest = 150;
  31. for (int c = 0; c < 7; c++)
  32. {
  33. if (temp[c] < smallest)
  34. {
  35. smallest = temp[c];
  36. }
  37.  
  38. }
  39. return smallest;
  40. }
  41.  
  42. public int highest()
  43. {
  44. int highest = -1;
  45. for (int c = 0; c < 7; c++)
  46. {
  47. if (temp[c] > highest)
  48. {
  49. highest = temp[c];
  50. }
  51. }
  52.  
  53. return highest;
  54. }
  55.  
  56. public double Average()
  57. {
  58. double average = 0;
  59. for (int c = 0; c < 7; c++)
  60. {
  61.  
  62. }
  63. return average;
  64. }
  65. }
  66. }

解决方法

使用单个循环非常容易:
  1. public double Average()
  2. {
  3. // Initialize smallest with the first value.
  4. // The loop will find the *real* smallest value.
  5. int smallest = temp[0];
  6.  
  7. // To calculate the average,we need to find the sum of all our temperatures,// except the smallest.
  8. int sum = temp[0];
  9.  
  10. // The loop does two things:
  11. // 1. Adds all of the values.
  12. // 2. Determines the smallest value.
  13. for (int c = 1; c < temp.Length; ++c)
  14. {
  15. if (temp[c] < smallest)
  16. {
  17. smallest = temp[c];
  18. }
  19. sum += temp[c];
  20. }
  21. // The computed sum includes all of the values.
  22. // Subtract the smallest.
  23. sum -= smallest;
  24.  
  25. double avg = 0;
  26. // and divide by (Length - 1)
  27. // The check here makes sure that we don't divide by 0!
  28. if (temp.Length > 1)
  29. {
  30. avg = (double)sum/(temp.Length-1);
  31. }
  32. return avg;
  33. }

猜你在找的C#相关文章