How to reset values in for loop? - c++

I need help figuring out where my code went wrong. I want to reset the values for the loop so that it isn't compiling because my output right now is using past input values in current calculation whereas I want the output to be different every time as though it is the firs time running the code. The code works fine when I don't use the while loop, but then I have to rerun the program each time. I want the output to prompt a new input every time, but not use past inputs in the new calculations. I know I'm not explaining it very well, but I'm just sort of lost. Anything helps!
This is my problem:
An approximate value of pi can be calculated using the series given
below:
pi = 4 · [ 1 – 1/3 + 1/5 – 1/7 + 1/9 ... + (–1 ^ n)/(2n + 1) ]
Write a C++ program to calculate the approximate value of pi using
this series. The program takes an input n that determines the number
of terms in the approximation of the value of pi and outputs the
approximation. Include a loop that allows the user to repeat this
calculation for new values n until the user says she or he wants to
end the program.
#include <cstdio>
#include <iostream>
using namespace std;
int main()
{
int n;
double sum=0;
cout << "Enter the number of terms to approximate (or zero to quit):\n";
cin >> n;
if (n == 0)
{
return 0;
}
while (n != 0)
{
{ for(int i=0;i<n;i++)
{
if (i%2==0)
{
sum += 1.0/(2*i+1);
}
else
{
sum += -1.0/(2*i+1);
}
}
cout.setf(ios::showpoint);
cout.precision(3);
cout << "The approximation is " << sum*4 << " using " << n << " terms." << endl;
}
cout << "Enter the number of terms to approximate (or zero to quit):\n";
cin >> n;
}
return 0;
}
This is my output:
This is what the output should be:

You do not reset sum before entering the for loop. Just add
sum=0;
before the for line.

Notice that 2.67 = 6.67 - 4.00.
You want your program to compute a sum for several values of n.
The sum must be initialized to 0 at the beginning of each calculation, inside the while loop.
Actually, it should even be declared there.

C++ doesn't require you to define variables at the start of a function, so it is perfectly legal to write:
while (n != 0)
{
double sum = 0.0;
this would solve your problem. Alternatively, if you want to keep the declaration of sum at the top of the function, just change your code to
while (n != 0)
{
sum = 0.0;

Related

Difference between two different peices of code telling a number is prime or not [duplicate]

This question already has answers here:
Why do we check up to the square root of a number to determine if the number is prime?
(13 answers)
Closed 1 year ago.
#include <iostream>
#include<cmath>
using namespace std;
int main()
{
int n;
cout << "Enter the no. and we will tell you whether it's Prime or Non-Prime \n";
cin >> n;
for (int i=2; i<n; i++) {
if (n%i== 0){
cout << "Non-Prime"<< endl;
break;
}
else {
cout << "Prime" << endl;
} break;
}
return 0;
}
#include <iostream>
#include<cmath>
using namespace std;
int main()
{
int n;
cout << "Enter the no. and we will tell you whether it's Prime or Non-Prime \n";
cin >> n;
bool flag=0;
for (int i=2; i<=sqrt(n); i++) {
if (n%i== 0){
cout << "Non-Prime"<< endl;
flag=1;
break;
}
}
if (flag ==0) {
cout << "Prime" << endl;
}
I wrote two pieces of code, simpler one is mine but the other second one having square root function involved was from internet. I want to program a simple code telling me whether a number is prime or not, so please tell me though both pieces of code do the same work what is logic in the second code and is it really necessary to write it in that way?
Mathematically, if a factor is greater than the square root of a number n, the other factor that would multiply with it to equal n is necessarily less than the square root of n.
Here,
Since sqrt(n) <= n, it saves a lot of computation time when n is a large number.
Check this answer.
You only need to go up to and including the square root of the number, since once you've pulled out a lower factor, the higher one drops out too.
Note that
i <= n / i
is a better way of specifying the stopping conditional: a std::sqrt takes a few clock cycles to evaluate and i is implicitly converted to a double in the evaluation of the expression. Only IEEE754 guarantees the result is the best it can be for an output double, standard C++ does not. Writing i * i <= n is also tempting but that can cause i to overflow with undefined results.
Writing i += 2 as the increment also yields a small gain, albeit at the expense of the purity of the approach (the function should be telling you that even numbers are not prime, not you telling it; in full generality you only need to iterate over the prime numbers up to and including the square root of n).

Why isn't my code running the whole program but not producing any errors?

I need to calculate the digits of a rational number that I get from the user.
The problem is that even though there is no errors in the code, the program running only part of the code. I'm working in Visual Studio.
int sumDigits(int a);
// main function
int main()
{
int ratioNum;
// Ask from the user to enter a rational number
cout << "Hello" << endl;
cout << "Please enter a rational number: ";
// Get the number from the user
cin >> ratioNum;
// Inform the user what is the sum of the digits
cout << "The sum of the digits are: " << sumDigits(ratioNum) << "." << endl;
return 0;
}
// Definition of function
int sumDigits(int a)
{
int digit = 0, sum = 0;
// As long as number is bigger than 0, continue
while (a > 0)
{
// Define a new verible - digit, as a number mudolo 10
digit = a % 10;
}
// kick out the units digit that we used
a / 10;
// Sum the digits of the number
sum = digit + a;
// Return sum to the main function
return sum;
}
You need a /= 10 instead of a / 10, and you need it inside the loop. Otherwise the loop will run forever because a never gets modified inside of it, so it can never become 0.
This will fix the infinite looping issue but the result will still not be correct. Why that is would be a different question though, and I'd invite you to learn proper debugging first (google how to debug C)! This will help you a lot more than copying a solution from here.
Your code isn't running the whole program because of these lines:
while (a > 0)
{
// Define a new verible - digit, as a number mudolo 10
digit = a % 10;
}
Inside the while loop, you're only assigning the value to the digit variable, but not changing the value of a, so the value of a always remains greater than 0. So your code gets stuck inside the while loop.
You should write
// kick out the units digit that we used
a /= 10;

i tried to calculate the sum of numbers between 1 and the inputted numer

The program demonstrates the operation of the loop operator.
Calculation of the sum of natural numbers. The positive integer n is introduced. The sum of natural numbers from 1 to n (inclusive) is calculated.
Check n for validity.
that was the work that I was given and I still don't know how to accomplish it and this is where left off:
#include <iostream>
int main()
{
int n = 0;
std::cout << "Enter n: ";
std::cin >> n;
int sum = 0;
for (int i = 1; i <= n; i += 2)
{
sum += i;
}
std::cout << sum << '\n';
return 0;
}
The anatomy of the for loop goes as this:
for(1;2;3)
What you do when entering the loop. In this case, setting i = 1.
The loop's end condition. You seem to be getting this right as well.
An operation to do every iteration of the loop. In your case, i += 2 will make i look like this on each iteration: 1 3 5 7 ... n. Get it? Because you are incrementing it by 2.
The mathematical operation you intend to do looks like this: sum = 1+2+3+...+n. To achieve this, you only need to adjust the 3rd part of the for loop.
One way to check what is going on inside the loop instead of just guessing it is "probing" the variables in it, like #molbdnilo proposed, by adding something like std::cout << i << std::endl; inside the loop.
Hope this helps you find your solution.

Estimating Pi using leibniz in C++

I am using the leibniz method for calculating pi. My program inputs an accuracy number for a calculation of π and then applies the leibniz infinite sum to find an approximate value of π within that accuracy.
I am trying to write a c++ while loop that will input an accuracy number (a double), the initial sum would be equal to zero and initially n would equal zero.
The denominator at n=0, d = 2*n+1 = 1, so the next term would be 4.0/1 = 4.0.
This would then be added to the sum and increment n. If This previous term was greater than the accuracy, the loop would continue.
When the previous term is smaller then the accuracy the number should be outputted and the loop should be exited.
My accuracy is never more than ±0.0001.
My not working code:
while(sum<accuracy)
{
int n = 0;
while(n>10) //this is here due to debugging
{
sum=-4/(2*n+1);
n++;
cout << sum << endl;
}
}
Question:
I am having a hard time coming up with a working while loop that can do what I described above. How do I create such a loop. Please provide an example with explanation.
Make sure that your sum-variable is float/double. It is like our friend commentet you are victim of integer division
double sum;
while(sum<accuracy){
int n=0;
while(n>10)
{
sum=-4.0/(2.0*n+1.0);
n++;
cout << sum << endl;
}
}

Calculation issue in C++

So in this program i am trying to print out the standard deviation of a set of numbers the user enters in. The formula to calculate standard deviation is correct (or as correct as it needs to be) so that is not the problem, but when i run the program everything goes well until the console prints out the results. It prints that totalStandardDeviation = nan
what exactly does than mean? is nan the same as nil? has it lost the value somehow and not been able to find it? thanks for any help you may provide.
#include <iostream>
#include <cmath>
using namespace std;
double returnStandardDeviation(double x, int counter);
double total;
int userInput = 1;
int counter = 0;
double x;
double x1;
double x2;
double standardDeviation;
double totalStandardDeviation;
int main(int argc, const char * argv[])
{
cout << "Please enter a list of numbers. When done enter the number 0 \n";
cin >> userInput;
while (userInput != 0) // As long as the user does not enter 0, program accepts more data
{
counter++;
x = userInput;
returnStandardDeviation( x, counter); // send perameters to function
cout << "Please enter next number \n";
cin >> userInput;
}
cout << "The standard deviation of your "
<< counter
<< " numbers is : "
<< returnStandardDeviation(x, counter);
return 0;
}
double returnStandardDeviation(double x, int counter)
{
x1 += pow(x,2);
x2 += x;
totalStandardDeviation = 0;
totalStandardDeviation += (sqrt(counter * x1 - pow(x2,2))) / (counter * (counter - 1));
return totalStandardDeviation;
}
NaN stands for "Not a number".
NaN can e.g. be the result of:
- Dividing by zero
- Taking the square root of a negative number
In your function, both of these could happen. Division by zero e.g. when counter is <= 1; and x1 and x2 are uninitialized (+= adds the value on the right to their current value - which was never set, and is therefore random gibberish), which can easily lead to your function trying to take the square root of some value < 0.
This expression
counter * x1 - pow(x2,2)
can very easily yield a negative number. You then proceed to take its square root. This would result in a nan.
Next, this one
counter * (counter - 1)
yields 0 when counter is 1. Dividing by zero gives nan.
Your formula is wrong. You are either dividing by zero or taking the square root of a negative number.
Check your formula!
Additional info:
NaN is "Not a number". It is an IEEE floating point value that signals an invalid results, like log(-1), or sqrt(-4).
Additionally, know that Positive Infinity and Negative Infinity are also floating point values.