查找升序列表中降序的第一个和最后一个数字
Finding the first and last number descending in an ascending list
我正试图找到一种方法来编写一个程序,该程序将接受"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变量,每次发现违规者时,都会更改索引号。
相关文章:
- 获取向量C++中第一个值和最后一个值的和
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 在类的第一个/最后一个实例存在之前/之后调用一对函数.有没有更好的方法?
- 查询事件日志.如何查询才能单独获取第一个和最后一个事件?
- 我必须更改我的数字最后一个数字和第一个数字,但不要使用仅带有整数或循环的函数.例如从 12345 到 52341
- 如何打印第一个和最后一个元素的和,然后打印第二个和倒数第二个元素的总和,依此类推
- 使用 STL 交换堆栈 C++ 中的第一个和最后一个元素
- 使用数组将最后一个最大值更改为第一个最小值
- "如何使用C++将字符串的第一个和最后一个索引返回到向量中?
- 查找数组的第一个和最后一个索引,其中 from 和 to 元素的顺序总和最大
- 数组:如何在指定索引之前显示数组的第一个和最后一个元素以及数组元素的差异?
- 输入文件中的第一个字符是输出文件中的最后一个字符,反之亦然
- 在向量C++中查找特定的第一个和最后一个索引<float>
- 如何使用第一个、中间和最后一个元素的中位数正确分区?
- 计算第一个和最后一个元素绝对差值较小的子序列 <= K
- COUT:最后一个字符串覆盖第一个字符串
- 获取第 n 项与 std::set 中第一个/最后一个的偏移量
- 如何使用递归返回单链表中的第n个最后一个元素
- 当第一个<=最后一个不满足时,C++标准对算法有什么看法?
- c++函数——哪个日期是第一个/最后一个