I am wondering if this is correct because each time i run my program it gives me 50050 on the console.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
usingnamespace 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 hope someone will help me on this. I am learning C++ from C++ for dummies and it doesn't show me the answer.
Your taking the sum of (0->100), in increments of 0.1.
Since SUM(a*Bi) = a*SUM(Bi), we can change the problem to SUM(0->1000) in increments of 1. ('a' = 10)
This sum can be calculated using the formula SUM(0->N) = N*(N+1)/2.
1000*1001/2 = 500500. Divide by 10 ('a') to get the result of your problem, which is the same you got.
I am copying code from my book. According to the book, it is a program that counts backwards using floating numbers. It starts from 100 and counts back. That's what i understood.
The snippet you posted starts at 0 and counts to 100, with increments of 0.1. The "current number" is added to the sum, thus making the calculaton: 0.1+0.2+0.3+0.4+...+99.9+100 = 50050.
I thought that due to i being less than or equal to 100 it should stop at 100. Also I happen to be a newbie at this, but what does the double variable do?
Double is a floating point type number usually consisting of 8 bytes.
Double and int are both number holding variables. int only allows counting numbers (0, 1, 2, -1, -2) where double allows floating point numbers or numbers with decimal places (3.14, 2.99, 0.25).
For the loop, the center is the condition. Your code says:\
Start x at 0.
Make i equal to 0.
While i is less than 100.0, accumulate i in x. ( x += i is the same as x = x + i. This is know as accumulation. You add a value to a variable and reassign the variable with the new value. This is the same thing as counting up.)
The variable i will stop at 100. But the variable x will have grow to accumulate all the values of i that has past.
Does that make sense?
Accumulators in a nutshell:
wholeNumbers = 0;
wholeNumbers + wholeNumbers + 1; // This how we count, we just don't think about it like this. Counting is accumulating.