查找升序列表中降序的第一个和最后一个数字

Finding the first and last number descending in an ascending list

本文关键字:第一个 最后一个 数字 降序 升序 列表 查找      更新时间:2023-10-16

我正试图找到一种方法来编写一个程序,该程序将接受"n"项并找出它是否升序。如果列表不是升序的,找到第一个违反这个顺序的数字,并打印它的索引位置i,然后找到最后一个违反它的数字。

ex: 2 3 4 2 3 2 3 4 1 -输出应该是:element#4是降序的&&元素#9是最后的下降

编辑:我已经解决了如何找到第一个数字而不是最后一个数字

下面是我的代码:
#include <iostream>
using namespace std;
int main(){
    int num, inputNum, i;
    int nextNum=0;
    int violator1=0, violator2=0; 
    int elementNum1=0, flag1=0;
    int elementNum2=0, flag2=0;
    cout << "Enter how much numbers you want to enter in list: ";
    cin >> num;
    for (i = 0; i < num; i++){
        cout << "Please enter a number: ";
        cin >> inputNum;
        if (inputNum >= nextNum){ 
            nextNum = inputNum;
        }
        else {
            flag1 = 1; /*The flag is set to '0' when the next number in      list has descended*/
            violator1 = inputNum;
            if (elementNum1 == 0) /*This condition will only run once because elementNum == 0 only once*/
                elementNum1 = i+1;
        }
    }
/*The flag value is determined within the loop to find the descending value*/
    if (flag == 0){ /*If the flag is UNchanged ie = 1*/
        cout << "These numbers are in ascending order." << endl;
    }
    else {
        cout << "These numbers are NOT in ascending order." << endl;
        cout << "Element Number '" << elementNum << "' was the violating number." << endl;
    }
    return 0;
}

我明白了。

要在一个已经下降到某一点的列表中找到最后一个违规者,你必须初始化一个新标志,并将其设置为在找到第一个违规者后改变。

在上面的例子中,在找到第一个违规者后,element1 == 0的条件应该为false。一旦该条件失败,就需要一个else语句将新标志更改为除1以外的其他标志,并需要一个新的element2变量,每次发现违规者时,都会更改索引号。

相关文章: