C 语言教程 在线

1809c-exercise-example40

参考方法:

#include<stdio.h>
#include <time.h>
#include <stdlib.h>

void reverse(int *numArray, int k);

int main()
{
    srand((int)time(0));
    int *numArray = NULL, m, n;
    printf("产生多少个1-100的随机数组元素?\n");
    scanf("%d", &n);
    numArray = (int*)calloc(n, sizeof(int));
    for (m = 0; m < n; ++m)
        numArray[m] = rand() % 101;//1-100之间随机数
    printf("逆序前:\n");
    for (m = 0; m < n; ++m)
        printf("%-4d", numArray[m]);
    reverse(numArray, n);
    printf("\n逆序后:\n");
    for (m = 0; m < n; ++m)
        printf("%-4d", numArray[m]);
    printf("\n");
    return 0;
}

void reverse(int *numArray, int k)
{
    int i, j;
    if (k % 2)//元素个数为奇数个时
    {
        for (i = 0, j = k - 1; i < k / 2 && j > k / 2; ++i, --j)
        {
            numArray[i] += numArray[j];
            numArray[j] = numArray[i] - numArray[j];
            numArray[i] -= numArray[j];
        }
    }
    else
    {
        for (i = 0, j = k - 1; i < k / 2 && j >= k / 2; ++i, --j)
        {
            numArray[i] += numArray[j];
            numArray[j] = numArray[i] - numArray[j];
            numArray[i] -= numArray[j];
        }
    }
}

1808c-exercise-example40

参考方法:

#include<stdio.h>
void reverse_print(int a[],int n);
int main(void)
{
    int a[10] = {0,1,2,3,4,5,6,7,8,9};
    printf("原始数组是:\n");
    for(int i = 0; i < 10;i++)
        printf("%-3d",a[i]);
    printf("\n排序后的数组:\n");
    reverse_print(a,10);
    return 0;
}

void reverse_print(int a[],int n)
{
    int i = 0;
    int j = n - 1;
    while(i < j)
    {
        if(i < j)
        {
            int temp;
            temp = a[i];
            a[i] = a[j];
            a[j] = temp;
        }
        i++;
        j--;
    }
    for(i = 0; i < n; i++)
        printf("%-3d",a[i]);
}

1807c-exercise-example40

参考方法:

#include<stdio.h> 
#include<stdlib.h>
#include<time.h>
int main()
{
    int i=0;
    int in[10];
    srand(time(NULL));
    printf("原数组:\n");
    for(i=0;i<10;i++){
        in[i]=rand()%11;
        printf("%d ",in[i]);
    }
    printf("\n逆序后数组:\n");
    for(i=9;i>=0;i--)
        printf("%d ",in[i]);
    return 0;    
} 

1806c-exercise-example40

参考方法:

#include<stdio.h>

int main()
{
    int a[10]={1,3,9,4,5,6,7,8,2,10};
    int *begin, *end;
    int temp,i;
    for(i=0;i<10;i++)
    {
        printf("%d ",a[i]);
    }
    printf("\n");
    begin=&a[0];
    end=&a[9];
    while(end>begin)
    {
        temp=*begin;
        *begin=*end;
        *end=temp;
        begin++;
        end--;
    }
    for(i=0;i<10;i++)
    {
        printf("%d ",a[i]);
    }
}

1805c-exercise-example40

参考方法:

#include <stdio.h>

int main(int argc, char *argv[])
{
    int i,num,a[10]={0,1,2,3,4,5,6,7,8};
    for(i=8;i>=0;i--){
        printf("%d ",a[i]);
    }
    return 0;
}