Practical way to quickly develop C++ skills

nickaelwen

The assignment is fine. It's the comparison in the if statement that's the issue. You have a/3 == b. The value of b will be converted to a double, which is fine since it's not very large. However, it's not always safe to assume that a whole number stored as a double will give you the number you expect. For example, try this code:

C++:
#include <iostream>
using namespace std;

int main ()
{
int i;
double j = 0;

for (i = 0; i < 10; i++) {
j += 0.1;
}

cout << (j == 1) << endl;

return 0;
}

It will output 0.

This is interesting, I tried to output j in in your code, it shows "1" but however it denies to say j equals integer "1".
Why is this? Need to dig in my text books.
Thanks.

cgorac

This is interesting, I tried to output j in in your code, it shows "1" but however it denies to say j equals integer "1".
Why is this?

It's because of rounding to default precision on output. You'll need to add in something like std::setprecision(16) into the mix, and you'll see that value j is actually less than 1 at the end of this piece of code.

ferdowsi

This is interesting, I tried to output j in in your code, it shows "1" but however it denies to say j equals integer "1".
Why is this? Need to dig in my text books.
Thanks.

0.1 is a repeating decimal in binary, so it has to round off when it stores it. When it adds it together, it won't add back up to 1. You can see it better using cgorac's method.

Cary Ferguson

Make a fun app that relates to your interest. That way you'll have so much fun making it that you'll finish it no matter how frustrated you get. I made a glass blowing app.

Daniel Duffy

C++ author, trainer
Make a fun app that relates to your interest. That way you'll have so much fun making it that you'll finish it no matter how frustrated you get. I made a glass blowing app.
Sounds cool. Do you have any links on what you did?

I learned C++ by writing CAD/CAM systems. Objects are very easy to find in those cases.

Cary Ferguson

I actually never put it online as it was for fun. But it's geared for beginners who are wondering what to make. It gives them shape choices by artists they like, proportions by fibonacci ratios and colors by the color wheel, artist mockery and fibonacci colors. Pretty fun stuff! I think I should give a spit shine and post it.

UIN

I recommend the book: "Accelerated C++" to beginners, who have basic programming skills.
The text is brief but deep and end of chapter (EoC) questions test understanding thoroughly.
Here's the ACCU Review:
I'm not sure if they have an edition that covers C++11, though.

Replies
16
Views
927
Replies
0
Views
2K
Replies
3
Views
782
Replies
3
Views
5K
Replies
0
Views
11K