python代码如何转成c代码_把这个python转换成C语⾔代码展开全部
# -*- coding: utf-8 -*-
import random
n, k = 30, 12
N = 10000000
cnt = 0
for _ in range(N):
GG = [random.random() for _ in range(n)]
for i in range(k-1, n):
if GG[i] > max(GG[:k-1]):
choice = i
if GG[choice] == max(GG):
cnt += 1
break
print(cnt)
print(cnt/N)#include
#include
#include
#define n 30
#define k 12
#define N 10000000
float max(float x[], int id)
{
float maxn = 0.0;
python代码转换for (size_t i = 0; i < id; i++)
{
if (maxn < x[i])
{
maxn = x[i];
}
}
return maxn;
}
int maxi(float x[], int id)
{
int maxn = 0;
for (size_t i = 0; i < id; i++)
{
if (x[maxn] < x[i])
{
maxn = i;
}
}
return maxn;
}
float *GGer()
{
static float res[n + 2];
for (size_t i = 0; i < n; i++)
{
res[i] = (float)(rand() * rand()) / (float)(RAND_MAX * RAND_MAX + 1); }
res[n] = max(res, k - 1);
res[n + 1] = max(res, n);
return res;
}
int cnter(float GG[])
{
static int res;
for (size_t i = k - 1; i < n; i++)
{
if (GG[i] > GG[n])
{
int choice = i;
if (GG[choice] == GG[n + 1])
{
res++;
}
break;
}
}
return res;
}
int main(int argc, char const *argv[])
{
// printer(mainloop(GGer, cnter([0])));
float *g;
int cnt;
srand(time(NULL)); //设置随机32313133353236313431303231363533e4b893e5b19e31333365653838数种⼦for (size_t i = 0; i < N; i++)
{
g = GGer();
cnt = cnter(g);
}
printf("CNT=\t%d\n", cnt);
printf("CNT/N=\t%f\n", (cnt / (float)N));
return 0;
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。