【问题标题】:Program With Array To Check For Increasing/Decreasing Numbers使用数组检查增加/减少数字的程序
【发布时间】:2016-09-11 05:19:23
【问题描述】:

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;
    }
}

【问题讨论】:

    标签: c++ arrays


    【解决方案1】:

    为了1.的需要,你必须多次调用increasing函数。所以你还需要一个整数advance来记住你的前进。

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

    然后你可以调用它(x 计算增加的​​次数,如 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;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-06-28
      • 1970-01-01
      • 1970-01-01
      • 2022-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-18
      相关资源
      最近更新 更多