python - 从按升序排序的数组中返回大于给定数字的最小数字的索引的 C 函数
问题描述
我正在翻译一些 Python 代码,以加深我对编程的理解。我有一个数组 P_array ,其中包含 1000 个递增的浮点数。我的任务是编写一个函数,该函数将返回 P_array[x] 大于 720 的第一个实例的索引。这是 python 和 C 代码,我在最后三行 python 代码中卡住了。
import numpy as np
import matplotlib.pyplot as plt
# Initializations
Dt = 1/32 # timestep Delta t
P_init= 30 # initial population
t_init = 0 # initial time
t_end = 30 # stopping time
n_steps = int(round(t_end/Dt))
t_array = np.zeros(n_steps+1)
P_array = np.zeros(n_steps+1)
t_array[0] = t_init
P_array[0] = P_init
#Eulers method
for i in range (1, n_steps + 1):
P = P_array[i-1]
t = t_array[i-1]
dPdt = 0.7 * P * (1-(P/750)) - 20
P_array[i] = P + Dt * dPdt
t_array[i] = t + Dt
index = np.where(P_array>=720)
x = ([x[0] for x in index])
print (x)
C代码
int main() {
int i, j, x = 1;
float dt, P_init, t_init, t_end;
dt = 0.03125;
P_init = 30;
t_init = 0;
t_end = 30;
int n_steps = 0;
n_steps = t_end/(float)dt;
float Parray[n_steps+1];
float Tarray[n_steps+1];
for (i=0; i<n_steps+1; i++) {
Parray[i]=0;
Tarray[i]=0;
}
Parray[0] = P_init;
Tarray[0] = t_init;
float P,t,dpdt,s,d;
while (x < n_steps+1) {
P = Parray[x-1];
t = Tarray[x-1];
dpdt = 0.7 * P * (1-(P/750)) - 20;
s = P + (dt * dpdt);
Parray[x] = s;
d = t + dt;
Tarray[x] = d;
x++;
printf("%f %f \n ",s,d);
}
return(0);
}
解决方案
感谢 user3629249,这是我的最终循环代码,它运行良好。
"double n = 720.00;
int m = 0;
for( j=0; j <n_steps+1; j++ ){
if( n < Parray[j]){
m = j;
break;
}
}
printf("%d\n", m);"
推荐阅读
- android - 使用自定义背景图像创建圆形按钮
- apache-kafka - Kafka 生产者和代理不同步超时
- python - Django `request.query_params.get("page")` 返回无?
- html - 具有表固定类的 Bootstrap 4 表不会设置背景颜色
- excel - 我的 excel 没有显示它在删除重复项后显示的系统消息 X 行被删除
- html - 音频标签无法从服务器加载音频文件
- javascript - thunk 和 action 完成后如何使用 redux 的当前状态?
- javascript - 单击时将 contentEditable 保存到 localStorage
- haskell - 当我在输入时遇到解析错误时,如何在 Haskell 中使用 (@) 运算符?
- java - 如何在 JFileChooser 中设置默认的新目录名称?