Sunday, October 6, 2019

c++ - Why does the program not calculate the value correctly?



I have a task. I need to evaluate the expression:



w = (3x + 6x + 9x ... + 90x) -15 , x = 0.03



The calculation of this expression should occur using a while loop.



I wrote the program code, but I get the impression that it does not work correctly.



Please see if my code is working correctly? I am very inexperienced = (



double x = 0.03;
double w, sum;
int counter1 = 0;
while (counter1 <= 90) {
counter1 += 3;
w = counter1 * x;
sum = sum + w;
}
sum = sum - 15;
cout << "Calculation result, w =: " << sum << endl;

Answer



Your problem is the first time through the loop:



sum = sum + w;


sum is uninitialised so it can contain any garbage.



You should always initialise variables:



double sum = 0;


Also, as @formerlyknownas_463035818 comments, your loop goes too far:



while (counter1 <= 90) {
counter1 += 3;
...


your last term will be 93 * x, not 90 * x as you intended.



So it should be:



while (counter1 < 90) {
counter1 += 3;
...

No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...