[英]How can I make a program to check if the array is in descending , ascending order or none of them?
此代碼僅允許用戶填充數組:
應該在不使用任何排序功能的情況下檢查它是按降序還是升序排列,或者都不檢查它們。 但是它不能正常工作,因為它既不上升也不下降,因此無法排序
#include <stdio.h>
int main ()
{
int array[10];
int i;
int c;
int d;
printf("Enter the element of array:\n");
for(i=0; i<10; i++)
{
scanf("%d",&array[i]);
}
for(i=0; i<10; i++)
{
printf("%d\n",array[i]);
}
for(i=0; i<9; i++)
{
if(array[i]<array[i+1])
{
c=1;
}
else if(array[i]>array[i+1])
{
d=1;
}
}
if(c==1)
{
printf("ASCENDING");
}
else if(d==1)
{
printf("DESCENDING");
}
else
{
printf("NONE");
}
return 0;
}
#include <stdio.h>
#define ASND 0
#define DSND 1
int main ()
{
int a[10];
int i = 0;
int order;
printf("Enter the element of array:\n");
for(i=0; i<10; i++) {
scanf("%d",&a[i]);
}
for(i=0; i<10; i++) {
printf("%d\n",a[i]);
}
for(i=1;i<10;i++){
if(a[i-1] < a[i]) {
order = ASND;
break;
}
if(a[i-1] > a[i]) {
order = DSND;
break;
}
}
if(i==10) {
printf("all elements are same\n");
return 0;
}
if(order == ASND) {
for(i=1;i<10;i++) {
if(a[i-1] > a[i]) {
printf("no order\n");
return 0;
}
}
printf("ascending order\n");
return 0;
}
for(i=1;i<10;i++) {
if(a[i-1] < a[i]) {
printf("no order\n");
return 0;
}
}
printf("descending order\n");
return 0;
}
打破升序或降序規則后,您將需要跳出循環,以便不重置已使用的升序或降序規則變量。
#include <stdio.h>
int main ()
{
int array[10];
int i = 0;
int c = 0;
int d = 0;
printf("Enter the element of array:\n");
for(i=0; i<10; i++)
{
scanf("%d",&array[i]);
}
for(i=0; i<10; i++)
{
printf("%d\n",array[i]);
}
for(i=0; i<9; i++)
{
if(array[i]<array[i+1])
{
c=1;
}
else if(array[i]>array[i+1])
{
d=1;
}
// Run of same value
else if (d==0 && c==0)
{
continue;
}
// Can't be both ascending and descending
if (d == 1 && c == 1)
{
d = 0;
c = 0;
break;
}
}
if(c==1)
{
printf("ASCENDING");
}
else if(d==1)
{
printf("DESCENDING");
}
else
{
printf("NONE");
}
return 0;
}
這是一個非常簡單且易讀的文件。 我認為它可以很好地完成工作! 僅需要一個循環來檢查它,對一個計數器進行遞增或遞減求和,然后進行檢查!
#include <stdio.h>
int main ()
{
int a[10];
int i = 0;
int order;
printf("Enter the element of array:\n");
for(i=0; i<10; i++) {
scanf("%d",&a[i]);
}
for(i=0; i<10; i++) {
printf("%d\n",a[i]);
}
int ascendingCount=0;
int descendingCount=0;
int num1=a[0];
for(int i=1;i<10;i++){
if(a[i]>=num1){
num1=a[i];
ascendingCount++;
}
else if(a[i]<=num1){
num1=a[i];
descendingCount++;
}
}
if(ascendingCount==9) printf("it is ascendingCount");
else if(descendingCount==9) printf("it is descending");
else printf("its nothing");
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.