Trying to self-teach, need guidance

So I'm thinking about going back to school and pursing a degree in CS. Figured before I dove right in that I'd try to teach myself C++ and see how it goes, but I've already ran into an issue. I'm using the Dummies guide to C++ and with Code::Blocks IDE. For some reason I cannot get this code to output correctly, its a for a loop and I typed it exactly the way it is in the book but it prints 50050 to the console. Here's the code:

#include <iostream>

using namespace std;

int main()
{
double x = 0.0;
double i;

for(i = 0.0; i <= 100.0; i += 0.1)
{
x += i;
}

cout << x << endl;

return 0;

}

I thought maybe I just had something in the IDE incorrectly configured or something, any help would be much appreciated.
Computer Science is not programming, but that's for someone else here to talk about.

What value were you expect in this program? The first issue I see is that you're trying to compare floating point numbers. This is fundamentally flawed http://floating-point-gui.de/
The book made it sound like it was a counter. I had assumed it would count to 100 in increments of 0.1.
it does, but notice that the code outputs the value of x, not i.
closed account (iN6qM4Gy)
Just make it so the code outputs i instead of outputting x inside the for loop. really x isn't even needed in this program. to make the code even shorter write it like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

using namespace std;

int main()
{
for(double i = 0.0; i <= 100.0; i += 0.1)
{
cout << i << endl;
}


return 0;

}
if you notice in your code you have: x += i;
This is saying in more simple terms: x = x + i;
i increments in 0.1 increments. So if you replace the variables with actual numbers (and assuming x = 0, you should always initialize your variables so you know what is in them at the start)
you get for the first few cases:

0 = 0 + 0.1 = 0.1; 1st case
0.1 = 0.1 + 0.2 = 0.3; 2nd case
0.3 = 0.3 + 0.4 = 0.7; 3rd case
0.7 = 0.7 + 0.5 = 1.2; 4th case
and so on and so forth. To do a count with the for loop there are a couple different ways to do it. First, in your code in the for loop you have:
1
2
3
for (i = 0.0; i <= 100; i+= .1) // this wont give you a count
// instead try this
for (i = 0.0; i <= 100; i) // this keeps i from incrementing allowing x to increment correctly 

or you can use the code as Yumixfan gives you and just output i, but you want to modify it a little
Thanks guys I got it working. I'm sure I'll have many more questions as I voyage through the world of programming. I'll probably be on here a lot, maybe not posting but at least searching through old post for some answers.
Topic archived. No new replies allowed.