Solve Do-while loop - c++

#include <iostream>
using namespace std;
int main()
{
double x = 1;
double y = 2;
int i = 1;
do
{
y /= 2.0;
x+= y;
++i;
cout << i;
}
while (x < 2.4);
}
I thought the output would be 2, but that is not correct. Can someone explain why?

Have a look at the condition which controls whether or not your loop will execute again. At the end of the first loop, the value of x is 2.0. Since this is less than 2.4, the loop runs a second time. In total that means i is incremented twice raising it to 3.

Related

No output due to large fractional values

#include<iostream>
#include<cmath>
using namespace std;
float san= 0.25 ; float var= 0.75;
int findFact(int n)//factorial
{
return n == 1 ? 1 : n * findFact(n - 1);
}
int findNcR(int n, int r)//combination nCr
{
return findFact(n) / (findFact(n - r) * findFact(r));
}
double prob(int s, int v){ //recursive function for probability
if(s>=5) return 1; if(v>=5) return 0;
double sum = 0;
int m = 5-s;
for( int i=0; i<=m; i++){
sum += prob(s+i,v+m-i)*findNcR(m,i)*pow(san,i)*pow(var,m-i);
}
return sum;
}
int main(){
cout<< prob(2,1);
}
In DEV C++, there is no output printed when I compile and run the above code. I think its because of large fractional values involved. Any idea how I can get the output?
Please check the logic you use in your double prob(int s, int v) method.
You are going to infinity recursive like
S=2 V=1
S=2 V=4
S=2 V=7
The base case for your recursion, s==5 or v==5 is never getting hit. As you call your function with s=2, every time the prob function is called it is setting m to 3, and so on the first iteration of the loop (when i==0) it calls prob with s=2 and v=v+3. As you start with v==1, it successively calls prob(2,1), prob(2,4), prob(2,7), etc... and never gets any further.
I don't know what probability distribution you are trying to code so I can't offer any specific advice on how to fix this.

Programm Output "nan"

I am trying to calculate PI with the infinite series. When I started my programm I excpected to get some wrong nummbers, but instead I get the output "nan".
Does anyone know why?
Here's the code:
#include <iostream>
using namespace std;
int main()
{
long double pi;
float x;
int y = 3;
bool loop = true;
while(true)
{
x=1/y;
y+2;
if(loop == true)
{
pi -= x;
loop = false;
}
else if(loop == false)
{
pi += x;
loop = true;
}
cout<<pi<<" ";
}
return 0;
}
The behaviour of your code is undefined as pi is not initialised when you read its value on adding or subtracting x to or from it. That accounts for the NaN: some compilers helpfully - in some ways - set uninitialised floating point variables to NaN.
x = 1 / y; sets x to 0 due to integer division. Did you want 1.0 / y?
y + 2; is a no-op. Did you want y += 2?
Note that you need to multiply the series by 4 to obtain pi, and this series converges especially slowly, some 300 terms are needed for two decimal places. And your starting value of y is wrong. Shouldn't it be 1?

Why this code produce 1?

Why this code produce 1? Someone, describe it for me pls.
#include <iostream>
using namespace std;
int main(){
int x = 0;
int y = 0;
if (x++&&y++){
y += 2;
}
cout << x + y << endl;
return 0;
}
Initially x and y are 0
Therefore x++ evaluates to false, and the second operand of && is never evaluated. x++ does increment x to 1. Since the condition is false, the conditional branch is not entered.
x + y is 1 + 0 which equals 1
user2079303 explains nicely (+1 by me already), as extension, I'll go a little more into detail:
if(x++) evaluates the value of x before the incrementation, so this little piece of code is equivalent to the following (need to buffer the old value!):
int tmp = x;
x++;
if(tmp)
Be aware that within c && cc, the second condition cc is not evaluated any more if c is already false! So if(x && y) is equivalent to
if(x)
{
if(y)
{
// ...
}
}
Putting all this together, your code is equivalent to this variant, where I separated the if clause into code lines each one containing only one single instruction:
int x = 0;
int y = 0;
int tmp = x;
x++;
if(tmp)
{
tmp = y;
y++;
if(tmp)
y += 2;
}
Suppose, your output now is quite obvious...

While Loop that increments a variable to a point

My goal for this program is to get input from the user for value 'y' and then multiply that value by 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, and then print the 10 results. Right now, when the user enters a value for 'y', the program just returns a list of zeros. Any idea what I'm doing wrong?
#include <iostream>
using namespace std;
int main(){
int x;
int y;
int z;
x = 0;
z = x * y;
cout << "enter y" << endl;
cin >> y;
while (x < 10) {
cout << z << endl;
x = x + 1;
}
}
The problem you have is that you don't actually calculate z inside the loop, so it will always be the value you calculated outside the loop. Statements and expressions can't be done retroactively.
But you have a worse problem than that, because you use y before you initialize it, which leads to undefined behavior.
You need to change the location of the y input to be before the calculation of z that should be inside the loop
The statement z = x * y should be inside your while loop for it to work.
What is happening now is that,each time it is printing the same value of z which is calculated initially as x(which is 0) and y(which is some garbage value as it has not been initialized) to give 0
The first problem occurring in your code is that try to assign z by multiplying x with y, but y is not assigned to a certain value => ERROR! That means you should get your user input before you assign z.
You may wonder why you get ten outputs of '0': Inside the loop you only print the value assigned to z to the console but z is already assigned before and not changed during the repetition.
#include <iostream>
using namespace std;
int main(){
int x;
int y;
int z;
x = 0;
z = x * y; // y is never assigned to a value
cout << "enter y" << endl;
cin >> y; // y got assigned here!
while (x < 10) {
cout << z << endl; // z stays the same in the loop
x = x + 1;
}
}

finding pi - using Machin's formula. Different iterations are giving same result

I've written a few programs to find pi, this one being the most advanced. I used Machin's formula, pi/4 = 4(arc-tan(1/5)) - (arc-tan(1/239)).
The problem is that however many iterations I do, I get the same result, and I can't seem to understand why.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
double arctan_series(int x, double y) // x is the # of iterations while y is the number
{
double pi = y;
double temp_Pi;
for (int i = 1, j = 3; i < x; i++, j += 2)
{
temp_Pi = pow(y, j) / j; //the actual value of the iteration
if (i % 2 != 0) // for every odd iteration that subtracts
{
pi -= temp_Pi;
}
else // for every even iteration that adds
{
pi += temp_Pi;
}
}
pi = pi * 4;
return pi;
}
double calculations(int x) // x is the # of iterations
{
double value_1, value_2, answer;
value_1 = arctan_series(x, 0.2);
value_2 = arctan_series(x, 1.0 / 239.0);
answer = (4 * value_1) - (value_2);
return answer;
}
int main()
{
double pi;
int iteration_num;
cout << "Enter the number of iterations: ";
cin >> iteration_num;
pi = calculations(iteration_num);
cout << "Pi has the value of: " << setprecision(100) << fixed << pi << endl;
return 0;
}
I have not been able to reproduce your issue, but here is a bit cleaned up code with a few C++11 idioms and better variable names.
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
// double arctan_series(int x, double y) // x is the # of iterations while y is the number
// then why not name the parameters accoringly? In math we usually use x for the parameter.
// prefer C++11 and the auto notation wherever possible
auto arctan_series(int iterations, double x) -> double
{
// note, that we don't need any temporaries here.
// note, that this loop will never run, when iterations = 1
// is that really what was intended?
for (int i = 1, j = 3; i < iterations; i++, j += 2)
{
// declare variables as late as possible and always initialize them
auto t = pow(x, j) / j;
// in such simple cases I prefer ?: over if-else. Your milage may vary
x += (i % 2 != 0) ? -t : t;
}
return x * 4;
}
// double calculations(int x) // x is the # of iterations
// then why not name the parameter accordingly
// BTW rename the function to what it is supposed to do
auto approximate_pi(int iterations) -> double
{
// we don't need all of these temporaries. Just write one expression.
return 4 * arctan_series(iterations, 0.2) - arctan_series(iterations, 1.0 / 239.0);
}
auto main(int, char**) -> int
{
cout << "Enter the number of iterations: ";
// in C++ you should declare variables as late as possible
// and always initialize them.
int iteration_num = 0;
cin >> iteration_num;
cout << "Pi has the value of: "
<< setprecision(100) << fixed
<< approximate_pi(iteration_num) << endl;
return 0;
}
When you remove my explanatory comments, you'll see, that the resulting code is a lot more concise, easier to read, and therefore easier to maintain.
I tried a bit:
Enter the number of iterations: 3
Pi has the value of: 3.1416210293250346197169164952356368303298950195312500000000000000000000000000000000000000000000000000
Enter the number of iterations: 2
Pi has the value of: 3.1405970293260603298790556436870247125625610351562500000000000000000000000000000000000000000000000000
Enter the number of iterations: 7
Pi has the value of: 3.1415926536235549981768144789384678006172180175781250000000000000000000000000000000000000000000000000
Enter the number of iterations: 42
Pi has the value of: 3.1415926535897940041763831686694175004959106445312500000000000000000000000000000000000000000000000000
As you see, I obviously get different results for different numbers of iterations.
That method converges very quickly. You'll get more accuracy if you start with the smallest numbers first. Since 5^23 > 2^53 (the number of bits in the mantissa of a double), probably the maximum number of iterations is 12 (13 won't make any difference). You'll get more accuracy starting with the smaller numbers. The changed lines have comments:
double arctan_series(int x, double y)
{
double pi = y;
double temp_Pi;
for (int i = 1, j = x*2-1; i < x; i++, j -= 2) // changed this line
{
temp_Pi = pow(y, j) / j;
if ((j & 2) != 0) // changed this line
{
pi -= temp_Pi;
}
else
{
pi += temp_Pi;
}
}
pi = pi * 4;
return pi;
}
For doubles, there is no point in setting precision > 18.
If you want an alternative formula that takes more iterations to converge, use pi/4 = arc-tan(1/2) + arc-tan(1/3), which will take about 24 iterations.
This is another way if some of you are interested. The loop calculates the integral of the function : sqrt(1-x²)
Which represents a semicircle of radius 1. Then we multiply by two the area. Finally we got the surface of the circle which is PI.
#include <iomanip>
#include <cmath>
#define f(x) sqrt(1-pow(x,2))
double integral(int a, int b, int p)
{
double d=pow(10, -p), s=0;
for (double x=a ; x+d<=b ; x+=d)
{
s+=f(x)+f(x+d);
}
s*=d/2.0;
return s;
}
int main()
{
cout << "PI=" << setprecision (9) << 2.0*integral(-1,1,6) << endl;
}