Get maximum and minimum from numbers

こ雲淡風輕ζ 提交于 2019-12-24 11:04:17

问题


I need to print maximum and minimum number from numbers. Problem is that when i set mn and mx to 0 it just wont work because when user write numbers 1 2 3 4 5 minimum is 0 and not 1 and thats the problem.

My code:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>

int main() {

    int x, mx = 0, mn = 0;
    int i = 1, n;

    scanf("%d", &n);
    for (i = 1; i <= n; i++) {
        printf("Your number %d:", i);
        scanf("%d", &x);
            if (x > mx) {
                mx = x;
            };
            if (x < mn) {
            mn = x;
            };
    };

    printf("minimum is: %d", mn);
    printf("maximum is: %d", mx);
    system("pause");
    return 0;
}

回答1:


Set both to the first value entered. Then use your current code as it is.

(Except for system("pause");. C does not need that.)




回答2:


to print maximum and minimum number from numbers.

Initialize mn,mx to the opposite extremes rather than both to 0. No need to make for a special case in the loop. Good code strives to reduce complexity of loops.

This easily and correctly detects the corner case when no minimum/maximum exist (the empty set).

#include <limits.h>

// int mx = 0, mn = 0;
int mn = INT_MAX;
int mx = INT_MIN;

...  code as before

if (mn > mx) {
  puts("No input encountered");
} else {
  printf("minimum is: %d\n", mn);
  printf("maximum is: %d\n", mx);
}


来源:https://stackoverflow.com/questions/52614201/get-maximum-and-minimum-from-numbers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!