有谁知道我如何获得连续输入之间的最大差异?

时间:2017-10-31 12:44:23

标签: c++ math

我得到了最高的数字和差异,但我不知道如何显示最大的差异,但我不知道从那里去哪里我只是想显示输入之间的最大差异。感谢

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    int integers;
    int highest = 0;
    int difference;
        int counter = 0;
    int lastInteger;
    vector<int> numbers;
    cout << "Please enter in integers and enter 0 to stop: ";
    while(cin >> integers)
    {
      if(integers == 0)
      {
          break;
      }
      counter ++ ; 
      if(counter > 1)
      {
      difference = integers - lastInteger;
        cout << difference << endl;
      }
      lastInteger = integers;
    }
    cout << "  The highest number is " << highest << endl;
    cout << "the Differnce is " << difference << endl;
}

1 个答案:

答案 0 :(得分:0)

引入一个新的整数变量maxDifference来保持最大差异并将其初始化为零。然后,每次为difference计算新值时,请将其与maxDifference进行比较,如果值更大,则将其值分配给maxDifference。像这样:

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    int integers;
    int highest = 0;
    int difference;
    int maxDifference = 0;
    int counter = 0;
    int lastInteger;
    vector<int> numbers;
    cout << "Please enter in integers and enter 0 to stop: ";
    while(cin >> integers)
    {
      if(integers == 0)
      {
          break;
      }
      counter ++ ; 
      if(counter > 1)
      {
      difference = integers - lastInteger;
      if (difference > maxDifference)
      {
        maxDifference = difference;
      }
        cout << difference << endl;
      }
      lastInteger = integers;
    }
    cout << "  The highest number is " << highest << endl;
    cout << "the Differnce is " << difference << endl;
    cout << "the maximal differnce is " << maxDifference << endl;
}

请注意我遵循您的编码风格,我认为应该改进。

作为一项练习,尝试将此工作用于消极差异。