数组是否升序

Array with whether if an array is ascending or not ascending

本文关键字:升序 是否 数组      更新时间:2023-10-16

所以问题是弄清楚数组是否升序,这意味着如果数组是 2,3,4,6,它将显示是它正在升序,如果是 3,2,5,6 它将显示 no 不升序。

我似乎无法让程序显示 0,这意味着不升序,我知道问题出在 for 循环或 if 语句中的某个地方,但我不知道如何解决它

#include <iostream>
using namespace std;
int ascending(int x[], int npts);
int main()
{
    int number[10];
    int num;
    cout<<"How many numbers would you like to enter? (max = 10) ";
    cin>>num;
    for(int i = 0; i<num; i++)
    {
         cout<<"Enter number ";
         cin>>number[i];

    }
    int asc = ascending(number, num);
    cout<<asc;
}
int ascending(int x[], int n)
{
   int count  = 0;
   for(int i = 0; i<n-1; i++)
   {
      if(x[i]<x[i + 1])
        count++;
      if(count <= n - 1)
        return 1;
      else
        return 0; 
    }
 }

您的问题出在升序函数中,您在第一次迭代后返回 1。 为了确定数字序列是否升序,必须遍历所有数字序列。但是,如果您发现一个在任何时候都不升序的数字,那么您可以立即返回 0。如果您安全地遍历所有这些而不返回 0,那么您就知道序列正在升序

int ascending(int x[], int n)
{
    for(int i = 0; i<n-1; i++)
    {
        if(x[i]>=x[i + 1])
            return 0
    }
    return 1
}
int ascending(int x[], int n)
{
    int i = 0;
    Do
    {
        if(x[i]> x[i + 1])
        return 0;
        i++;
    } while (i < n-1);
    return 1;
}