Zeng-fh 2022-02-06 14:24 采纳率: 89.8%
浏览 49
已结题

给定一个数组,获取最大值及其下标并输出。有一个是错的。请问怎么分析这4段代码呀?

A


#include <stdio.h>
#define LEN 10

int main(int argc, char** argv)
{
    int i, max, index = 0;
    int arr[LEN] = {7, 2, 1, 3, 6, 9, 4, 10, 5, 8};
    int *p = arr;

    max = arr[0];
    for (i = 0; i < LEN; ++i)
        if (*(p + i) > max)
        {
            max = *(p + i);
            index = i;
        }

    printf("max = arr[%d] = %d\n", index, max);

    return 0;
}

B


#include <stdio.h>
#define LEN 10

int main(int argc, char** argv)
{
    int i, max, index = 0;
    int arr[LEN] = {7, 2, 1, 3, 6, 9, 4, 10, 5, 8};

    max = arr[0];
    for (i = 0; i < LEN; ++i, ++arr)
        if (*arr > max)
        {
            max = *arr;
            index = i;
        }

    printf("max = arr[%d] = %d\n", index, max);

    return 0;
}

C

#include <stdio.h>
#define LEN 10

int main(int argc, char** argv)
{
    int i, max, index = 0;
    int arr[LEN] = {7, 2, 1, 3, 6, 9, 4, 10, 5, 8};
    int *p = arr;

    max = arr[0];
    for (i = 0; i < LEN; ++i)
        if (p[i] > max)
        {
            max = p[i];
            index = i;
        }

    printf("max = arr[%d] = %d\n", index, max);

    return 0;
}

D

#include <stdio.h>
#define LEN 10

int main(int argc, char** argv)
{
    int i, max, index = 0;
    int arr[LEN] = {7, 2, 1, 3, 6, 9, 4, 10, 5, 8};
    int *p = arr;

    max = arr[0];
    for (i = 0; i < LEN; ++i, ++p)
        if (*p > max)
        {
            max = *p;
            index = i;
        }

    printf("max = arr[%d] = %d\n", index, max);

    return 0;
}

  • 写回答

2条回答 默认 最新

  • Code_流苏 C/C++领域优质创作者 2022-02-06 15:55
    关注

    B是错的,如图数组名arr其实代表首地址,它不能进行自增运算。

    img


    这类题做题是有技巧的,就本题来说,它让你获取一个数组所有数组元素中的最大值及其下标,那就要用到for循环进行遍历,那它出题的关键点就是
    1.for(;;)中的语句:

    img

    2.判断语句:

    img


    3.数组跟指针的联系:

    img

    A,C,D都符合给定一个数组,获取最大值及其下标并输出的要求。

    以上仅供参考,如有任何疑问,可以评论回复,看到即回。
    希望对题主有所帮助!可以的话,点个采纳!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 2月14日
  • 已采纳回答 2月6日
  • 修改了问题 2月6日
  • 创建了问题 2月6日

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗