-1

Maybe the title isn't what it should, or maybe its a duplicate, but either way,i'm stuck and couldnt find the right answer here or anywhere else.

I`m used to php, and recently started learning c++.

I need to convert a php loop that loops trough a julian date/time. In php this is quite easy.

In php i just create a variable with the julian date/time and then start looping with decimal numbers. An example:

<?php

    $jd = 2445874.74375;

    for($x=0; $x<=300; $x++) {
        echo "new jd = ". $jd;
        $jd = $jd + 0.5; // half a day
    }

?>

Which then result in the following number sequence

jd = 2445874.74375
jd = 2445875.24375
jd = 2445875.74375
jd = 2445876.24375
jd = 2445876.74375
jd = 2445877.24375
jd = 2445877.74375
jd = 2445878.24375
jd = 2445878.74375

I'm new to c++, so i just tried to copy the same thing but changed the syntax so it compiles and runs in C++.

int main() {

    double jd = 2445874.74375; // I figured i need a double here?

    for(int i = 0; i <= 300; i+=1) {

        cout << jd << endl;

        jd = jd + 0.5;
    }
}

But when i run the code, the results show a total different number then i would expect. From what i understand and read, the number doesn't really change, but is formatted differently... Output looks like this ->

2.44587e+06
2.44588e+06
2.44588e+06
2.44588e+06
2.44588e+06
...
2.44589e+06

But i need a number like the original one. So what am i missing, what do i not understand and most importantly how can restore the number formatting like the original julian date/time number i inserted into the double? I need the jd like 2445874.74375 to appear in its original format to make another function work. So how i can make this loop working, like its working in php? I already noticed that in C++ defining a variables the right way seems to be very important, where as in php it seems to be less important. But either way, i don't get it. I have read about integers, floating points, doubles, char and strings etc. But the more i look into it, the complexer it becomes for me...

2

1 Answer 1

3

I was quite surprised by the result myself. Apparently cout outputs doubles in scientific notation by default. Using the std::fixed stream manipulator should fix it.

int main()
{
    double jd = 2445874.74375; // I figured i need a double here?

    for (int i = 0; i <= 300; i += 1) {

        std::cout << std::fixed << jd << std::endl;

        jd = jd + 0.5;
    }
    system("pause");
}
1
  • Ah GREAT!, this works like it should. So the number stays the same but it formatting changes.
    – Esocoder
    Jan 6, 2019 at 12:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.