C语言 - 如何打印输入数组的最大数字?

时间:2016-10-05 15:22:17

标签: c arrays printing

我希望能够打印出用户输入的最大年龄以及最小的年龄。

另外,我注意到我的程序没有包含小数点后面的数字。它只会说25.00,而不是25.25。

非常感谢任何帮助!

./myprogram < inputs.txt

3 个答案:

答案 0 :(得分:1)

我认为这会有所帮助。 对于小数点,您必须将数组声明为float FLT_MAX 这些宏定义float的最大值。在使用 FLT_MAX 之前,您应该inclue float.h 标题文件。

#include <stdio.h>
#include <float.h>

int main(void)
{
float age[11];
float total = 0;
int i = 1;
float average;
float largestInput = 0.0;
float smallestInput = FLT_MAX;

do
{
    printf("# %d: ", i);
    scanf("%f", &age[i]);
    total = total + age[i];
    //here i am checking the largest input
    if (age[i]> largestInput){
     largestInput = age[i];
    }
    //here i am checking the smallest input
    if (age[i] < smallestInput) {
      smallestInput = age[i];
    }
    i = i + 1;
} while (i <= 10);

average = (total / 10);
printf("Average = %.2f\n", average);
printf("Largest Input Is = %.2f\n", largestInput);
printf("Smallest Input IS = %.2f", smallestInput);
return 0;
}

答案 1 :(得分:0)

的伪代码。保留两个额外的变量。 long maximumInput,smalltestInput。

组 largestInput = smalltestInput = age [0];

for (i = 0; i < 10; i++) {
  if age[i]> largestInput{
     largestInput = age[i];
  }
  if age[i] < smallestInput {
      smalltestInput = age[i];
  }
}

按您喜欢的方式打印

答案 2 :(得分:0)

您的代码在我的系统上正常运行。我已将您的代码修改为不是Windows特定的,并向您展示如何计算输入的最小和最大数字。我们的想法是不断将当前条目与当前最小和最大数字进行比较,并根据需要更改最小和最大数字。下面的代码还显示了如何从数组索引0开始。

#include <stdio.h>


int main()
{
    int age[10];
    float total = 0;
    int i = 0;
    float average;
    int large = -9999;
    int small = 9999;

    do
    {
        printf("# %d: ", i+1);
        scanf("%d", &age[i]);       
        total = (total + age[i]);

        if( age[i] < small )
        {
            small = age[i];
        }

        if( age[i] > large )
        {
            large = age[i];
        }

        i++;

    } while (i < 10);

    average = (total / 10.00);
    printf("Smallest = %d Largest = %d \n", small, large);
    printf("Average = %.2f\n", average);
}


# 1: 30
# 2: 40
# 3: 50
# 4: 2
# 5: 3
# 6: 4
# 7: 6
# 8: -1
# 9: 4
# 10: 5
Smallest = -1 Largest = 50 
Average = 14.30