我正在编写一个函数来生成数组,但是我必须应用许多if语句,这些语句会影响输出。
我尝试仅列出它们,但我认为它以某种方式影响了我的输出,看起来也很麻烦。
static double [] solve (equation b, int k)
{
double [] a = null;
if (b.c > 1)
{
a = new double[k];
for (int i = 0; i < k; i++)
{
b.x0 = (b.c*b.x0)/(b.y0) + (b.d*b.x0);
b.y0 = b.e*(b.x0 + 1)*b.y0;
a[i] = b.y0;
}
}
if (b.d > 0)
{
a = new double[k];
for (int i = 0; i < k; i++)
{
b.x0 = (b.c*b.x0)/(b.y0) + (b.d*b.x0);
b.y0 = b.e*(b.x0 + 1)*b.y0;
a[i] = b.y0;
}
}
if (1 > b.e || b.e > 0)
{
a = new double[k];
for (int i = 0; i < k; i++)
{
b.x0 = (b.c*b.x0)/(b.y0) + (b.d*b.x0);
b.y0 = b.e*(b.x0 + 1)*b.y0;
a[i] = b.y0;
}
return a;
有没有一种方法可以对我的if语句进行分组,以便如果我的参数在所需范围内,我将得到结果,如果不是,我将得到'null'。 (还有更多的if语句,但这可以使您理解。)
答案 0 :(得分:3)
您的所有循环都执行相同的操作,因此在if
中具有所有条件的单个or
应该这样做。喜欢,
static double[] solve(equation b, int k) {
if (b.c > 1 || b.d > 0 || 1 > b.e || b.e > 0) {
double[] a = new double[k];
for (int i = 0; i < k; i++) {
b.x0 = (b.c * b.x0) / (b.y0) + (b.d * b.x0);
b.y0 = b.e * (b.x0 + 1) * b.y0;
a[i] = b.y0;
}
return a;
}
return null;
}
答案 1 :(得分:0)
将您的条件分为多个私有方法。