简体   繁体   English

找出数字之间的最大差

[英]Finding the maximum difference between numbers

Given n numbers, find maximum difference between some two of them. 给定n个数字,找出其中两个之间的最大差。 For example, for input data 1 2 7 -6 we have 13=7-(-6). 例如,对于输入数据1 2 7 -6,我们有13 = 7-(-6)。 But my code doesn't seem output correct results: 但是我的代码似乎没有输出正确的结果:

#include <iostream>
#include <algorithm>
int main()
{
    int n, j, k;
    std::cin >> n;
    int *a;
    a = new int[n];

    for (j=0; j<n; j++)
    {
        std::cin >> a[j];
    }

   std::sort(a, a + sizeof(int));


    k=a[n-1]-a[0];
    std::cout << k;

    delete [] a;

    return 0;
}

As Olivier answered, your mistake is in the call to std::sort(), but I want to point out that unless this is mandatory for your task (it may be part of an homework), You don't need to sort the array nor you need an array too. 正如Olivier回答的那样,您的错误在于对std :: sort()的调用中,但我想指出的是,除非这对您的任务是必需的(它可能是家庭作业的一部分),否则您无需对数组,也不需要数组。

#include <iostream>
#include <climits>

int main() {
    int n, j, a;
    int max = INT_MIN;
    int min = INT_MAX;

    if ( std::cin >> n  &&  n > 0 ) {
        while ( j < n  &&  std::cin >> a ) {
            if ( a < min ) min = a;
            if ( a > max ) max = a;
            j++;
        }    
        std::cout << max - min;
    }
    return 0;
}

Your problem is when you call std::sort 您的问题是当您调用std :: sort时

You do: 你做:

std::sort(a, a + sizeof(int));

So you actually only sort 4 elements (sizeof(int)=4 most of the time). 因此,您实际上只对4个元素进行排序(大多数情况下,sizeof(int)= 4)。 For correct result you could do: 为了获得正确的结果,您可以执行以下操作:

std::sort(a, a+n); (better)

or 要么

std::sort(a, &a[n]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM