Yahoo奇摩知識+將於 2021 年 5 月 4 日 (美國東部時間) 終止服務。自 2021 年 4 月 20 日 (美國東部時間) 起,Yahoo奇摩知識+服務將會轉為唯讀模式。其他Yahoo奇摩產品與服務或您的Yahoo奇摩帳號都不會受影響。如需關於Yahoo奇摩知識+ 停止服務以及下載您個人資料的資訊,請參閱說明網頁。

匿名使用者
匿名使用者 發問時間: 電腦與網際網路程式設計 · 6 年前

<急!!>關於指標,陣列, 程式高手請進?

編輯一程式,輸入5個數字成陣列,並撰寫2個指標,

指標1為由大到小

指標2為由小到大

原文: (a.) Write a program that reads 5 distinct integers from

the keyboard and place them in array data[5]. The program

then will sort the array into ascending and descending order and

print the sorted lists. The program must not change the original

array or create any other integer arrays.

The solution to this program requires two pointer arrays as

shown in the following figure. The first pointer array is

rearranged so that it points to the data in ascending sequence.

The second pointer array is rearranged so that it points to the

data in descending sequence

(b.) Same as (a) except that the program asks the user

to input the number of distinct integers first. Then the

program reads those integers from the keyboard and place

them in array data.

Note that! Those three arrays data,

ascending, descending must be allocated by

using calloc( ) function in the program.

1 個解答

評分
  • ?
    Lv 7
    6 年前
    最佳解答

    #include<stdio.h>

    #include<stdlib.h>

    int cmp0(int*a,int*b){return*a>*b;}

    int cmp1(int*a,int*b){return*a<*b;}

    void srt(int**a,int sz,int cmp(int*,int*)){

    int i,j;

    for(i=0;i<(sz-1);++i)

    for(j=i+1;j<sz;++j)

    if(cmp(a[i],a[j])){int*t=a[i];a[i]=a[j];a[j]=t;}

    return;

    }

    void prt0(int*a,int sz){int i;for(i=0;sz>i&&printf(" %d",a[i]);++i);printf("\n");}

    void prt1(int**a,int sz){int i;for(i=0;sz>i&&printf(" %d",*a[i]);++i);printf("\n");}

    int main(){

    { // a

    int n,i;

    int *a,**a0,**a1;

    n=5;

    a=calloc(n,sizeof(*a));

    a0=calloc(n,sizeof(*a0));

    a1=calloc(n,sizeof(*a1));

    for(i=n-1;i>=0;--i)a0[i]=a1[i]=&a[i];

    for(printf("Enter %d integers:\n",n),i=0;i<n&&scanf("%d",a+i);++i);

    srt(a0,n,cmp0);

    srt(a1,n,cmp1);

    printf("Ascending:"); prt1(a0,n);

    printf("Descending:"); prt1(a1,n);

    printf("original:"); prt0(a,n);

    if(a )free(a ),a = NULL;

    if(a0)free(a0),a0= NULL;

    if(a1)free(a1),a1= NULL;

    } // end of A

    { // B

    int n,i;

    int *a,**a0,**a1;

    if(0 >= printf("how many intergers do you want to enter: ") ||

    1 > scanf("%d",&n) ||

    1 >= n ) return 1;

    a=calloc(n,sizeof(*a));

    a0=calloc(n,sizeof(*a0));

    a1=calloc(n,sizeof(*a1));

    for(i=n-1;i>=0;--i)a0[i]=a1[i]=&a[i];

    for(printf("Enter %d integers:\n",n),i=0;i<n&&scanf("%d",a+i);++i);

    srt(a0,n,cmp0);

    srt(a1,n,cmp1);

    printf("Ascending:"); prt1(a0,n);

    printf("Descending:"); prt1(a1,n);

    printf("original:"); prt0(a,n);

    if(a )free(a ),a = NULL;

    if(a0)free(a0),a0= NULL;

    if(a1)free(a1),a1= NULL;

    } // end of B

    return 0;

    }

還有問題?馬上發問,尋求解答。