Adding decimal numbers were my exam question.
Our teacher said the right code is this (Look below), but it doesn’t work what’s the problem
This is the question: 9/10-11/12+13/14-15/16+….49/50 Write a c++ program to calculate this question
Here is the code:
#include <iostream>
using namespace std;
int main()
{
double x;
int p = 1;
double s = 0;
for (x = 9.0; x < 49.0; x + 2.0)
{
s = s + x / (x + 1) * p;
}
p = -p;
cout << "Total: " << s << endl;
}
>Solution :
Well, this may be what you want:
#include <iostream>
int main( )
{
int sign { 1 };
double sum { };
for ( std::size_t x = 9; x <= 49; x += 2 )
{
std::clog << "sum == " << sum << '\n';
// here you have to cast both x and x+1 to double
sum += static_cast<double>( x ) / static_cast<double>( x + 1 ) * sign;
sign = -sign;
}
std::cout << "\nTotal: " << sum << '\n';
}
Also, don’t use anything except integral types for the initialization variable of a for-loop. For example, use std::size_t or int.
The result:
sum == 0
sum == 0.9
sum == -0.0166667
sum == 0.911905
sum == -0.0255952
sum == 0.918849
sum == -0.0311508
sum == 0.923395
sum == -0.0349387
sum == 0.9266
sum == -0.0376859
sum == 0.928981
sum == -0.0397693
sum == 0.930819
sum == -0.0414032
sum == 0.932281
sum == -0.042719
sum == 0.933471
sum == -0.0438013
sum == 0.93446
sum == -0.0447071
Total: 0.935293
As you can see, in this case after 20 iterations (because (49-9)/2 == 20), the total/sum will be 0.935293 so I hope this is what your teacher had in his/her mind.