C++ 程序三个随机选取的数字构成等差数列的概率


我们有数字数组n,任务是求出三个随机选取的数字构成等差数列的概率。

示例

Input-: arr[] = { 2,3,4,7,1,2,3 }
Output-: Probability of three random numbers being in A.P is: 0.107692
Input-:arr[] = { 1, 2, 3, 4, 5 }
Output-: Probability of three random numbers being in A.P is: 0.151515

以下程序中使用的方法如下

  • 输入正整数数组
  • 计算数组大小
  • 应用以下公式来求三个随机数字构成等差数列的概率

    3 n / (4 (n * n) – 1)

  • 输出结果

算法

Start
Step 1-> function to calculate the probability of three random numbers be in  AP
   double probab(int n)
      return (3.0 * n) / (4.0 * (n * n) - 1)
Step 2->In main()
   declare an array of elements as   int arr[] = { 2,3,4,7,1,2,3 }
   calculate size of an array as  int size = sizeof(arr)/sizeof(arr[0])
   call the function to calculate probability as probab(size)
Stop

示例

#include <bits/stdc++.h>
using namespace std;
//calculate probability of three random numbers be in AP
double probab(int n) {
    return (3.0 * n) / (4.0 * (n * n) - 1);
}
int main() {
    int arr[] = { 2,3,4,7,1,2,3 };
    int size = sizeof(arr)/sizeof(arr[0]);
    cout<<"probability of three random numbers being in A.P is : "<<probab(size);
    return 0;
}

输出

Probability of three random numbers being in A.P is: 0.107692

更新于: 2019 年 11 月 20 日

121 次浏览

开启你的 职业生涯

完成课程获得认证

开始
广告