简体   繁体   中英

C++ for loop using an array

I know this is a basic question, but I'm a Python user very new to C++

I need to compute a function (cosmology.bias_eff) using a for loop for which the input parameter (Mass_min) needs to be multiplied by an array (M_ratio) .

I am making a mistake here by using two for loops .

vector<double> M_ratio = {1.0,0.9,1.1,1.05,1.1,1.15,1.2,1.25,1.2};
double Mass_min = 2e13;
double Delta0 = 200.0;

for (redshift=0.0;redshift<1.7;redshift=redshift+0.2)
{   
    for (size_t i=0; i<M_ratio.size(); i++)
    {
        double Delta = cosmology.DeltaR(Delta0, redshift);

        double bias_eff = cosmology.bias_eff(M_ratio[i]*Mass_min,redshift,Delta);

        cout << bias_eff <<"," << endl;
    }
}

What I want is , for each redshift in the for loop, I want Mass_min to be multiplied by M_ratio ,

ie for redshift = 0.0, Mass_min = Mass_min*1.0 , for redshift = 0.2, Mass_min = 0.9*Mass_min and so on.

You need only a single loop:

vector<double> M_ratio = {1.0,0.9,1.1,1.05,1.1,1.15,1.2,1.25,1.2};
double redshift;
int i;
for (redshift=0.0,i=0; i<M_ratio.size(); i++,redshift+=0.2) {
  double Delta = cosmology.DeltaR(Delta0, redshift);
  double bias_eff = cosmology.bias_eff(M_ratio[i]*Mass_min,redshift,Delta);
  cout << bias_eff <<"," << endl;
}

On each iteration, redshift in incremented by 0.2, at the same time i is incremented by one. Inside the loop the needed computation takes place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM