簡體   English   中英

計算一個數字在沒有數組的情況下重復的次數(c++)

[英]Counting times that a number repeats without array(c++)

我需要一個程序來獲取 0-20 之間的 100 個數字並計算重復次數最多的數字的重復。
這是我以較少的輸入量(10而不是100)得到的,但這是錯誤的。

#include <iostream>
using namespace std;

int main() {
    int num, x,c;

    for(int i=1; i<=10; i++) {
        cin >> num;
        if(num==x)
            c++;
        else
            x=num;
    }

    cout << c;
    return 0;
}

假設您的意思是最長的連續序列,這是您可以做到的一種方法:

#include <iostream>

int main() {
  int max_val = 0, max_len = 0;  // Overall longest
  int cur_val = 0, cur_len = 0;  // Current

  for (int i = 0; i < 10; ++i) {
    int val;
    std::cin >> val;     // read 1 number
    if (val == cur_val)  // if still counting the same, increment the length
      ++cur_len;
    else {  // else, set the max and reset current
      if (cur_len > max_len) {
        max_len = cur_len;
        max_val = cur_val;
      }
      cur_len = 1;
      cur_val = val;
    }
  }

  // consider the very last sequence
  if (cur_len > max_len) {
    max_len = cur_len;
    max_val = cur_val;
  }

  // Result
  std::cout << "Longest seq: " << max_val << ", length: " << max_len << '\n';
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM