簡體   English   中英

C 函數從按遞增順序排序的數組中返回大於給定數字的最小數字的索引

[英]C function that returns index of smallest number greater than a given number from an array sorted in increased order

我正在從 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)

代碼

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);
}

關於:*C 函數返回大於遞增數組給出的最小數字的索引

以下建議代碼:

  1. 執行所需的功能

現在,建議的代碼:

// C function that returns index of smallest number greater than given from increscent array

#include <stdio.h>

int main( void )
{
    //
    // assume code to generate array, sorted ascending
    size_t arraySize;
    float sortedArray[ arraySize ];
    //

    //
    // assume code to input target value
    float targetValue;
    //

    for( size_t i=0; i<arraySize; i++ )
    {
        if( targetValue > sortedArray[i] )
        {
            printf( "index into array = %zu\n", i );
            break;
        }
    }
}

感謝 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);"

暫無
暫無

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

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