首页 > 解决方案 > 显示 4 个整数中的最大值和最小值,同时显示它们的位置

问题描述

这是我在大学学习 Comp-Sci 课程的第一年,在这门课程之前我没有任何编程经验。我目前正在尝试为类分配编写一个 C 程序,该程序接受 4 个整数输入,然后显示 4 个中的最大和最小,同时还说明输入最大和最小整数的位置。

注意:我不允许使用任何函数、数组或循环(除了下面给出的 while 循环,但仅此而已)。

我的教授提供了一个大纲来帮助入门。

这是我的代码:

#include <stdio.h>

int main(void)
{
    int x1, x2, x3, x4;
    int xlarge, xsmall, ixlarge, ixsmall;

    while (1)
    {
        printf("enter x1, x2, x3, x4:\n");
        scanf("%d%d%d%d", &x1, &x2, &x3, &x4);

        /*     add code to calculate xlarge, xsmall,
         *     ixlarge, ixsmall
         * --> between here */

        if ((x1 > x2) && (x1 > x3) && (x1 > x4))
            x1 = xlarge;
        else if ((x2 > x1) && (x2 > x3) && (x2 > x4))
            x2 = xlarge;
        else if ((x3 > x1) && (x3 > x2) && (x3 > x4))
            x3 = xlarge;
        else if ((x4 > x1) && (x4 > x2) && (x4 > x3))
            x4 = xlarge;

        if ((x1 < x2) && (x1 < x3) && (x1 < x4))
            x1 = xsmall;
        else if ((x2 < x1) && (x2 < x3) && (x2 < x4))
            x2 = xsmall;
        else if ((x3 < x1) && (x3 < x2) && (x3 < x4))
            x3 = xsmall;
        else if ((x4 < x1) && (x4 < x2) && (x4 < x3))
            x4 = xsmall;

        if (xlarge = x1)
            ixlarge = 1;
        else if (xlarge = x2)
            ixlarge = 2;
        else if (xlarge = x3)
            ixlarge = 3;
        else if (xlarge = x4)
            ixlarge = 4;

        if (xsmall = x1)
            ixsmall = 1;
        else if (xsmall = x2)
            ixsmall = 2;
        else if (xsmall = x3)
            ixsmall = 3;
        else if (xsmall = x4)
            ixsmall = 4;

        /* <-- and here */

        printf("largest = %4d at position %d, ", xlarge, ixlarge);
        printf("smallest = %4d at position %d\n", xsmall, ixsmall);
    }

    while (1) getchar();
    return 0;
}

据我了解,如果该程序满足条件,则应将其分配xlargexsmall输入,对于ixlargeand 也是如此ixsmall。但是,我在尝试运行该程序时遇到的一个问题是,xlarge显然xsmall没有初始化,我不知道从哪里开始。

标签: c

解决方案


看代码:

它应该是xlarge = x1而不是x1 = xlarge类似地xsmall = x1,因为它是 xlarge 存储 x1 的值,而不是相反。

你也可以像这样使用你的 if-else:

if ((x1 > x2) && (x1 > x3) && (x1 > x4))
{
xlarge = x1;
ixlarge = 1;
}
else if ((x2 > x1) && (x2 > x3) && (x2 > x4))
{
xlarge = x2;
ixlarge = 2;
}

等等...


推荐阅读