程序与数组来检查增加/减少的数字

Program With Array To Check For Increasing/Decreasing Numbers

本文关键字:数字 增加 数组 检查 程序      更新时间:2023-10-16

初学c++的学生在这里开始学习使用数组的不同方法。我正试着把下面的程序放在一起。它应该要求用户输入一组数字,这些数字将进入一个数组。这组数字可以在用户想要的任何点增加或减少。

例如:

1 2 3 4 9 8 7 4 5 6 10 11 12 20 19 18 17

程序将根据这组数字进行检查,并说明每次增加或减少的原因。现在程序将返回"增加"或"减少"。

例如,根据它返回的上述数字集运行它:

增加减少减少

然而,我有两个问题:

  1. 我认为它不能正确地解释数组中发生的所有变化(增加和减少)。

  2. 我现在必须返回发生的变化的数量,而不是"减少"/"增加"。也就是说,在上面的例子中,它将返回"3",因为有1个真值和2个假值。

如果有人能提出建议,我将非常感激。

非常感谢!!

#include <iostream>
using namespace std;
bool increasing(int arr[], int n);

int main()
{
    int arr[20], n;
    cout << "Enter a set of Increasing/Decreasing numbers (ex. 1 2 3 6 5 4 7 8 9 3 2 1)." << endl;
    cout << "Press 'Enter' to see results" << endl;
    while (cin >> n)
    {
        for (int i = 0; i <= n; i++)
        {
            cin >> arr[i];
        }
        cout << (increasing(arr, n) ? "increasing" : "decreasing") << endl;
    }
    return 0;
}

bool increasing(int arr[], int n)
{
    int x = 0;
    for (int i = 0; i < n - 1; i++)
    {
        if (arr[i] < arr[i + 1])
        {
            x++;
        }
    }
    if (x == n - 1)
    {
        return true;
    }
    else
    {
        return false;
    }
}

供1。你必须多次调用increasing函数。因此,您还需要一个整数advance来记住您的进度。

bool increasing(int arr[], int& advance, int n);

你可以用(x counts the number of increase,如2所述)

    int advance = 0;
    do {
       int x = 0;
       cout << (increasing(arr, advance, n, x) ? "increasing " : "decreasing ") << x << endl;
    } while (advance < n-1);

你可以用

实现它
bool increasing(int arr[], int& advance, int n, int& x)
{   assert(advance < n-1);
    x = 0;
    bool doesIncrease = arr[advance] < arr[advance + 1];
    bool isStable = arr[advance] == arr[advance + 1];
    if (doesIncrease) {
      for (int i = advance+1; i < n - 1; i++)
      {
          if (arr[i] < arr[i + 1])
          {
              x++;
          }
      }
    }
    else if (isStable) {
       ...
    }
    else { // decreasing
      for (int i = advance+1; i < n - 1; i++)
      {
          if (arr[i] > arr[i + 1])
          {
              x++;
          }
      }
    };
  return doesIncrease;
}