圆盘找数问题.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. #include <iostream>
  2. //编译预处理命令
  3. #include<iostream>
  4. using namespace std;
  5. //圆盘类circle的定义与实现
  6. class circle {
  7. private:
  8. int num[20];
  9. int Max[4];
  10. int Min[4];
  11. int sum_max;
  12. int sum_min;
  13. public:
  14. // 构造函数,初始化 num 数组
  15. circle() {}
  16. circle(int arr[20]) {
  17. for (int i = 0; i < 20; ++i)
  18. num[i] = arr[i];
  19. }
  20. // 计算连续四个数之和最大的数和其和值
  21. void maxSum() {
  22. int maxSum = 0;
  23. int index = 0;
  24. for (int i = 0; i < 17; ++i) {
  25. int sum = num[i] + num[i + 1] + num[i + 2] + num[i + 3];
  26. if (sum > maxSum) {
  27. maxSum = sum;
  28. index = i;
  29. }
  30. }
  31. sum_max = maxSum;
  32. for (int i = 0; i < 4; ++i)
  33. Max[i] = num[index + i];
  34. }
  35. // 计算连续四个数之和最小的数和其和值
  36. void minSum() {
  37. int minSum = 999999;
  38. int index = 0;
  39. for (int i = 0; i < 17; ++i) {
  40. int sum = num[i] + num[i + 1] + num[i + 2] + num[i + 3];
  41. if (sum < minSum) {
  42. minSum = sum;
  43. index = i;
  44. }
  45. }
  46. sum_min = minSum;
  47. for (int i = 0; i < 4; ++i)
  48. Min[i] = num[index + i];
  49. }
  50. // 输出圆盘的数列、最大和最小的四个数及其和值
  51. void show() {
  52. for (int i = 0; i < 20; ++i)
  53. cout << num[i] << " ";
  54. cout << endl;
  55. cout << "Max=" << sum_max << endl;
  56. for (int i = 0; i < 4; ++i)
  57. cout << Max[i] << " ";
  58. cout << endl;
  59. cout << "Min=" << sum_min << endl;
  60. for (int i = 0; i < 4; ++i)
  61. cout << Min[i] << " ";
  62. cout << endl;
  63. }
  64. };
  65. int main(void)
  66. {
  67. circle a; //圆盘类的对象a
  68. int i,test[20];
  69. //输入数据test
  70. for (int i = 0; i < 20; ++i)
  71. cin >> test[i];
  72. a = circle(test);
  73. for (int i = 0; i < 20; ++i)
  74. cin >> test[i];
  75. circle b(test); //圆盘类的对象b
  76. //测试圆盘a,b
  77. cout << "圆盘a:" << endl;
  78. a.maxSum();
  79. a.minSum();
  80. a.show();
  81. cout << "圆盘b:" << endl;
  82. b.maxSum();
  83. b.minSum();
  84. b.show();
  85. return 0;
  86. }