我需要找出给定数组是否按降序排序......
我得到了输出,但在门户网站中显示为错误答案。
这是我的代码。
#include<stdio.h>
int main()
{
int n,a[15],i,k=0;
scanf("%d",&n);
for(i=1;i<=n;i++)
{ scanf("%d",&a[i]);}
for(i=1;i<=n;i++)
{
if(a[i]<a[i+1])
k++;
}
if(k==0)
printf("yes");
else
printf("no");
return 0;
}
帮我解决一下......
答案 0 :(得分:4)
数组从0
到size - 1
编入索引。所以,如果你有
int array[15];
元素为a[0]
到a[14]
。但是在您的代码中,您从a[1]
开始到a[15]
并可能尝试访问a[15]
,这是不安全的内存并会导致问题。
所以你应该先改变你的for循环。
您应该将其更改为
for( i = 0 ; i < n ; i++ )
{
scanf("%d",&a[i]);
}
for( i = 0 ; i < n - 1 ; i++ )
{
if( a[i] < a[i+1] )
{
k++;
break;
}
}
在第二个for循环中,你应该循环到i < n - 1
,否则,在
if(a[i]<a[i+1])
i = n
时,您将尝试使用n + 1
元素访问a[i+1]
,这可能超出范围。
一旦发现数组不按降序排列以节省时间,您也可以退出循环。
您还必须确保a[15]
足以存储所有值(即,作为输入给出的值的数量不应超过15,请检查问题陈述以确保这一点)
答案 1 :(得分:3)
你应该在for循环中从0
开始数组索引。
使用此
for(i=0;i<n;i++)
在第二个for循环中你应该使用
for(i=0;i<n-1;i++) // you need to compare up to second last element with last, so run loop upto `i<n-1`
例如,如果您输入n = 5
循环将适用于0
到4
如果break;
的值增加
k
for(i=1;i<=n;i++)
{
if(a[i]<a[i+1]){
k++;
break; // if k increments break the loop.
}
}
答案 2 :(得分:2)
你在这里。:)
#include <stdio.h>
#define N 15
int main(void)
{
int a[N];
int i, n;
printf( "Enter number of elements in the array (not greater than %d: ", N );
scanf( "%d", &n );
if ( N < n ) n = N;
printf( "Enter %d elements of the array: ", n );
for ( i = 0; i < n; i++ ) scanf( "%d", &a[i] );
i = 0;
while ( i++ < n && !( a[i-1] < a[i] ) );
if ( i == n ) puts( "The array is sorted in the descending order" );
else puts( "The array is not sorted in the descending order" );
return 0;
}
程序输出可能看起来像
Enter number of elements in the array (not greater than 15: 15
Enter 15 elements of the array: 10 10 9 9 9 8 7 6 5 5 4 3 2 1 0
The array is sorted in the descending order
至于你的代码然后这个循环
for(i=1;i<=n;i++)
{
if(a[i]<a[i+1])
k++;
}
是不安全的,因为在表达式i+1
中使用索引a[i+1]
可以访问数组之外的内存。
此外,您还必须检查输入的n值是否小于15,即数组的大小,因为您使用索引范围[0, n]
。
在第一个循环中,索引必须从0开始。否则,数组的第一个元素将不会被初始化。
答案 3 :(得分:1)
首先,定义数组a [15]:
int n,a[15],i,k=0;
并使用变量n来控制其大小
scanf("%d",&n);
for(i=1;i<=n;i++)
{ scanf("%d",&a[i]);}
然后你需要保持n&lt; = 15。
p.s。,数组在Matlab中以'1'开头,但在C中以'0'开始。
答案 4 :(得分:-1)
我不太同意别人对阵列索引的看法,不知道是否存在[i + 1]和使用break的问题。我会补充说,当此输入数组中的所有数字相等时,它仍会在代码中递减。如果这是一个问题,你可以添加另一个if语句,检查它是否会在任何地方减少,并使用另一个变量,说更改以检查是否满意。
int change = 0;
for(i=0;i<n;i++)
{
if(a[i]<a[i+1])
k++;
if(a[i]>a[i+1])
change++;
}
if(k==0 && change > 1)
printf("yes");
else
printf("no");
检查问题陈述是否允许降序等情况。如果它不适合这个,否则罚款。