我在做运动时遇到问题,这是问我:
编写一个程序,读取一个整数序列,如果该序列是有序的(升序或降序),则输出true,否则为false。请记住,如果一个数字与以下数字具有相同的值,则不会破坏顺序。
序列以0结尾。请勿将此数字视为序列的一部分。该序列始终至少有一个数字(不包括0)。
样本输入1:
9 8 7 6 5 4 3 2 1 0 样本输出1:
真正 样本输入2:
1 2 3 3 9 0 样本输出2:
真正 样本输入3:
1 2 5 5 2 3 0 样本输出3:
假
我要解决的代码中有一个错误。
Scanner sc = new Scanner(System.in);
int as = 0;
int ds = 0;
int eq = 0;
int n = sc.nextInt();
int a;
int num = sc.nextInt();
for(int i = 1 ;i < n ; i++)
{
a = sc.nextInt();
while(a != 0)
{
if (a < num) ////// descending order
{
num = a;
ds = 1;
break;
}
else if ( a == num ) ////////equal
{
num = a;
eq = 1;
break;
}
else //////////ascending order
{
num = a;
as = 1;
break;
}
}
}
if(ds == 1 && as ==1 && eq==1 )
{
System.out.println("false");
}
else if ( (as == 1 && eq ==1) || ds ==0)
{
System.out.println("true");
}
else if ( (ds ==1 && eq==1) || as ==0)
{
System.out.println("true");
}
}
我已经检查了我的代码,任务在第3次测试中显示失败。任务显示我的输出为true,而我的输出为false。我到处显示错误的地方都运行我的代码。为什么会这样呢?
我的代码有些脏乱,请您接受一种更简单,更短的方法来解决此问题,或者告诉我我的错误可能是什么,拜托,非常感谢您的时间和回答