如何选择前n个项? [英] How to select the first n terms?

查看:79
本文介绍了如何选择前n个项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

for(i=0;i<500;i++)
{
    x=valuex[i];
    y=valuey[i];

    A[i][0]=x+y;
    A[i][1]=x*x+3*y;
    A[i][2]=x+2*y*x;
    ……
    A[i][99]=x/2+20*y;
}


在上面的代码中,有100个项:A [i] [0]〜A [i] [99],实际上,我想使用A [i] [j]的前n个项,而"n"是用户输入的数字,我如何有效地实现这一点,谢谢您的帮助.
最好的祝愿.


In the above code,there are 100 terms:A[i][0]~A[i][99], In fact, I want to use the first n terms of A[i][j],and "n" is the input number by user, how can I realize this efficiently,Thank you for your help.
Best wishes.

推荐答案

很好的问题,尽管我看不到真正的应用程序是什么.当我正确理解您的问题后,您只想计算
的前n个项
Nice question, although I don''t see what the real application is. When I understood your question correctly, you want to compute only the first n terms of
A[i][0]=x+y;
A[i][1]=x*x+3*y;
A[i][2]=x+2*y*x;
……
A[i][99]=x/2+20*y;



因此n是j的极限.正确吗?

至少有两种主要方法可以实现此目标:

(1)插入if语句



thus n being the limit for j. Correct?

There are (at least) two principal approaches of how you can go about that:

(1) Interspersing if statements

while (1)
{
    if (0 >= n) break;
    A[i][0]=x+y;

    if (1 >= n) break;
    A[i][1]=x*x+3*y;

    if (2 >= n) break;
    A[i][2]=x+2*y*x;
     ……

    if (99 >= n) break;
    A[i][99]=x/2+20*y;
    break;
}



这不是很优雅,但可能比方法2更快:

(2)将算术项放在函数数组中,然后在该数组上循环.



That is not elegant, but probably faster than approach number 2:

(2) Placing the arithmetic terms in an array of functions and then looping over that array.

typedef double PolyFunc (double x, double y);

double f0 (double x, double y)
    {return x + y;}

double f1 (double x, double y)
    {return x*x + 3*y;}

...

static PolyFunc* sFunctions[100] = {&f0, &f1, ...};

void ComputeArray (int n)
{
    ...
    for (int j = 0; j < n; ++j)
        A[i][j] = sFunctions[j] (x, y);
}



希望对您有所帮助.



Hope that helps.


关于您的问题有很多问题...
但是...

There are many questions about your question...
but...

switch (n)
{
case 99: A[i][99]=x/2+20*y;
...
case 2:   A[i][2]=x+2*y*x;
case 1:   A[i][1]=x*x+3*y;
case 0:   A[i][0]=x+y;
}



会很快.使用switch让编译器对if变体进行一些优化.
僵尸程序可能会更快一些:



will be very fast. Using switch let the compilers make some optimization over the if variant.
A bit confusing bot probably faster:

switch (99-n)
{
case 0:   A[i][99]=x/2+20*y;
...
case 97:   A[i][2]=x+2*y*x;
case 98:   A[i][1]=x*x+3*y;
case 99:   A[i][0]=x+y;

}


这篇关于如何选择前n个项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆