-3

This is part of my code that calculates xi using a class cosmology.xi_DM. I am very new to C++, so please bear with me!

double redshift = 0.75;
  string method = "CAMB";
  vector<double> r = {1., 2.};

  double xi = 0.;
  for (int i=0; i<r.size(); i++)
    xi = cosmology.xi_DM(r[i], method, redshift);

    cout << "xi_DM(z=" << redshift << ") = " << xi << endl;

However, when I print it, I only get the value of xi for r = 2.. It does not print xi for r = 1.. Why is this so?

user3397243
  • 567
  • 2
  • 10
  • 20
  • 1
    Your `cout` is *outside* the `for` loop. If you want it *inside*, but `{` and `}` around the block of code to be in the `for` loop. – crashmstr Oct 16 '15 at 12:22
  • @MrLister: thank you for pointing it out! – user3397243 Oct 16 '15 at 12:22
  • 2
    You're used to Python, aren't you? – Mr Lister Oct 16 '15 at 12:22
  • @MrLister Exactly!! I have never used C++ before!! – user3397243 Oct 16 '15 at 12:22
  • 2
    This should be covered by any good book, tutorial, or class instruction on C++. You should consider finding a resource to learn some of the basics. – crashmstr Oct 16 '15 at 12:24
  • @crashmstr As I had told you before, I am a complete beginner. I still don't understand why few people have downvoted my question. They would have started similarly!! – user3397243 Oct 16 '15 at 12:26
  • @user3397243 first link from google search of "C++ for loop" is [Statements and flow control](http://www.cplusplus.com/doc/tutorial/control/), which explains this in great detail. If you had searched first, you would have already found an answer. (In other words, Stack Overflow is a *great place* for questions, but prehaps not the *best place* for page one learning of a language). – crashmstr Oct 16 '15 at 12:28
  • Urgent read: [The Definitive C++ Book Guide and List](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – Ivan Aksamentov - Drop Oct 16 '15 at 13:07

2 Answers2

1

You've missed brackets:

for (int i=0; i<r.size(); i++)
{
    xi = cosmology.xi_DM(r[i], method, redshift);

    cout << "xi_DM(z=" << redshift << ") = " << xi << endl;
}
Alexander Stepaniuk
  • 6,217
  • 4
  • 31
  • 48
1

Your cout << ... instruction is not in the loop.

Try this:

for (int i=0; i<r.size(); i++)
{
    xi = cosmology.xi_DM(r[i], method, redshift);

    cout << "xi_DM(z=" << redshift << ") = " << xi << endl;
}
CiaPan
  • 9,381
  • 2
  • 21
  • 35