我怎样才能在一系列数字中找到一个缺失的数字

How can I find a missing number in a sequence of numbers?

本文关键字:数字 一个 一系列      更新时间:2023-10-16

数字应输入为:

53,55,57,58,54

输出:

丢失的号码是56

输入应该可以是任意数量的数字。

这就是我目前所拥有的:

#include <iostream>
#include <vector>
#include <string>
using namespace std;
int getMissingNo (int a[], int n)
{
    int i, total;
    total  = (n+1)*(n+2)/2;   
    for ( i = 0; i< n; i++)
       total -= a[i];
    return total;
}
int main()
{
    int a[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    cout << "Enter number of numbers in sequence: ";
    int numInSeq;
    cin >> numInSeq;
    cout << endl;
    cout << "Enter numbers in sequence: ";
    for (int i = 0; i < numInSeq; i++)
    {
        cin >> a[i];
    }
    cout << endl;
    int miss = getMissingNo(a,numInSeq);
    cout << "Missing number: " << miss << endl << endl;
    return 0;
}

我唯一缺少的是能够输入用逗号分隔的数字,并且我需要编辑getMissingNo,这样它可以是任何数字序列,而不仅仅是以1开头的数字序列。

如果您知道范围,则简单的解决方案。

  • 对于给定的范围,设S是该范围内所有数字的总和
  • 对于一个缺少数字的给定数组,设MS为该数组中数字的和

缺少的编号是S-MS

相关文章: