从C到Python的重新编码

2024-04-19 14:09:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我基本上是C语言的外行,我正在学习Python。我需要为Python编写下面(用C)描述的例程:

#include <stdio.h>
#include <math.h>

main()
{
    float   hold[26], hnew[26];
    float   dt, dx;
    float   t, s;
    float   ho;
    float   time;
    float   f1, d2h;

    int i;
    int nx, nlx;
    int n, nend;
    int kount, kprint;


    dt  = 5.0;
    dx  = 10.0;
    t   = 0.02;
    s   = 0.002;
    nx  = 11;
    nlx = nx-1;


    ho = 16.0;
    for( i = 1;  i <= nx;  i++ )
    {
        hold[i] = ho;
        hnew[i] = ho;
    }

    hold[nx] = 11.0;

    printf("\t\t\t\thead\t\t\t\t      time\n\n");
    kount  = 1;
    kprint = 2;

    time = dt;
    nend = 100;


    for( n = 1;  n <= nend;  n++ )
    {
            /* update solution */

        for( i = 2;  i <= nlx;  i++ )
        {
            f1 = dt*t/s;
            d2h = ( hold[i+1] - 2.0*hold[i] + hold[i-1])/(dx*dx);
            hnew[i] = hold[i] + (f1*d2h);
        }

        for( i = 1;  i <= nlx;  i++ )
        {
            hold[i] = hnew[i];
        }


        if( kount == kprint )
        {
            for( i = 1;  i <= nx;  i++ )
            {
                printf(" %.2f",hold[i]);
            }
            printf("   %6.2f\n",time);
            kount = 0;
        }

        time  = time + dt;
        kount = kount + 1;
    }
}

这是我对Python的尝试:

import numpy as np
dt = 5.0
dx = 10.0
t = 0.02
s = 0.002
nx = 11
nlx = nx - 1
ho = 16.0

hold = np.zeros(nx+1)
hnew = np.zeros(nx+1)

for i in range(nx):
    hold[i] = ho
    hnew[i] = ho

hold[nx] = 11.0

但是,我无法克服这个问题,因为我不知道printf函数的Python对应函数。这个函数在Python中的正确形式是什么?它指的是什么?你知道吗


Tags: fortimedtfloatintf1nxhold
3条回答

要打印类似于C的printf,以下是一个示例:

f = 3.25645
g = 3.14159265358979

for fl in (f,g):
    print(f'{fl:.2f}')


3.26
3.14

print中的第一个fformat说明符。大括号中的f表示将数字视为浮点数。你知道吗

它只是print()(见下面的一个小程序)

squares = []
for x in range(14):
 squares.append(x**2)

squares

squares2 = [x**2 for x in range(100)]

print (squares2) 

在Python中只使用print().format。你知道吗

例如:

x, y = 1, 2

print("x = {0}, y = {1}".format(x, y))

Here's the doc

相关问题 更多 >