如何将INT数字[1]的值与数字[2] C 进行比较

  • 本文关键字:数字 比较 INT c++ numbers
  • 更新时间 :
  • 英文 :


我需要创建一个将接受5个输入的程序,然后我应该显示5个输入的最高值。但是存在问题,我需要将number[0]的值与number[1]进行比较,以获取可用的最高数字。而且,我需要确保,如果用户输入与以前相同的数字,则不应接受,并告诉用户输入其他数字。这是我提出的...

int i,number[5],highest,max = number[i] + 1;    
int main(){
clrscr();
for(int i=0; i<5; i++){
    cout<<"nEnter number :";
    cin>>number[i];
    if(number[i] > max){
        cout<<"nHighest number is: "<<number[i];
    }
    else if (number[i] == number[i]){
        cout<<"nDo not repeat the same number twice!";
        i=i-1;
    }
}

还要注意您的else if (number[i] == number[i])总是会触发的,因为您将数字与本身进行比较。

int i,number[5],highest,max = number[i] + 1;

因为我只是开始init,然后i = 0。因此,max =数字[0] 1 = 1。您必须将所有数字输入到数组:

for(int i=0; i<5; i++){
    cout<<"nEnter number :";
    cin>>number[i];
}

比较它:

max = number[i] + 1;  
for(int i=0; i<5; i++){
    if(number[i] > max){
        cout<<"nHighest number is: "<<number[i];
    }
}

检查std::cin >>的结果:您可以获得无效的输入(例如if(! std::cin >> number[i]) { std::cout << "wrong input received"; return -1; }

使用最小值初始化最大值:std::numeric_limits<int>::min();,因此第一个数字将永远是第一个最大值。当输入较高时,您还应更新Max。

如果您只需要检查上一个值,请检查我不是零(没有以前的值),然后检查值[i]的值[i-1]。但是,如果您需要所有唯一的数字,则应在循环中检查所有以前的数字。

仅在循环后完成最大值的输出(在循环内仅用于调试)

您的代码有很多错误。这是写这篇文章的一种方法。

#include <iostream>
int main() {
  // Loop iterators
  unsigned int i = 0;
  unsigned int j = 0;
  // Data storage -- expecting only positive values.
  unsigned int number[5];
  unsigned int max = 0;  
  bool duplicate;
  // No incrementation here, as we want to skip invalid cases
  for (i = 0; i < 5; ) {
    duplicate = false;
    std::cout << "nEnter number: ";
    std::cin >> number[i];
    // Check that we don't have the same number in twice
    for (j = 0; j < i; ++j) {
      if(number[i] == number[j]) { 
        std::cout << "nDo not repeat the same number twice!" << std::endl;
        duplicate = true;
      }
    }
    // If a duplicate has been found, skip the rest of the process.
    if (duplicate) {
      continue;
    }
    // Is this a new maximum?
    if (number[i] > max) {
      max = number[i];
    }
    ++i;
  }
  std::cout << "Highest number is : " << max << std::endl;
  return 0;
}

最新更新