C ++中的最高/最低/和

时间:2017-04-08 13:48:25

标签: c++ for-loop

首先,我是编程的超级初学者。

因此,我尝试创建一个C ++代码,该代码将读取用户输入的5个数字,然后使用for显示最高数字,最低数字和数字总和。到目前为止,我已经这样做了:

#include <iostream>
using namespace std;

int main()
{
  int n, i, h, l, s;

  cout<<"Enter 5 numbers:\n";

  for (i=0; i<5; i++)
  {
      cin>>n;
      s+=n;

      if (n>l)
      {
          n=h;
      }
      else
      {
          n=l;
      }
  }

  cout<<"The highest number is "<<h<<", the lowest is "<<l<<" and the sum is "<<s<<".\n";

  return 0;

}

但这是错的,我感到很惭愧。有人可以开导我吗?提前谢谢。

1 个答案:

答案 0 :(得分:0)

int main()
{
  int n, i, h, l, s = 0;    // initialize (s = 0)

  cout<<"Enter 5 numbers:\n";

  for (i=0; i<5; i++)
  {
      cin>>n;
      s+=n;

      // first time
      if( i == 0 ) {
          h = l = n;
          continue;
      }

      if( n > h )       // l → h
      {
          h = n;        // reverse
      }
      else if( n < l )  // minimum check
      {
          l = n;        // reverse
      }
  }

  cout<<"The highest number is "<<h<<", the lowest is "<<l<<" and the sum is "<<s<<".\n";

  return 0;

}