Why is my variable value not resetting to 0? - c++

Working on a C++ program that calculates the value of pi. I can run it once correctly and it will output the desired value. But the part of the program where it asks the user if they want to run again, that value of pi will not be correct according to the formula. I can't seem to figure out where I am going wrong here.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
int seqNum; // Declares variable for user input
char response; // Will hold char if user wants to rerun the program or not.
// Welcome Message and prompts user to input an integer
cout <<"Welcome to the Calculating Pi Program!\n";
cout <<"Please enter an integer greater than 0: \n";
// Assigns user input to the seqNum variable
cin >> seqNum;
// While loop to validate user input
while (seqNum < 1)
{
cout <<"ERROR: You must enter an greater than 0\n";
cout <<"Please enter an integer greater than 0: \n";
cin >> seqNum;
}
double pi = 0;
for (int i=0; i <= seqNum; i++)
{
double sum = 1.0/(2*i+1);
if (i % 2 == 0)
pi += sum;
else
pi -= sum;
if (i == seqNum)
{
pi *= 4;
cout << fixed << setprecision(50) << pi << endl;
pi = 0;
i = 0;
cout << "Do you want to run again (Y/N):";
cin >> response;
if (response == 'Y' || response == 'y')
{
cout << "Please enter an integer greater than 0: \n";
cin >> seqNum;
}
else
return 0;
}
}
return 0;
}

You're not resetting your loop index. If I understand correctly your intent, you should add i = -1; in the true part of if (response == 'Y' || response == 'y'). The comment by user4581301 is also good advice.

When your calculations run again in your for loop, the index starts at 1 instead of 0 because in for loops the (;;i++) happens after the code block, every time it loops. A super easy fix is to just assign i=-1; when you reset (I wouldn't recommend this dirty fix, it was to demonstrate the issue).

Related

Collect positive floats & output the average when negative integer is input

I'm trying to write a program that reads in positive float numbers from the user and then when the user's is a negative number, gives the average of the numbers, excluding the negative.
#include <iostream>
using namespace std;
int main() {
float av_number, total = 0, input;
do {
for (int i = 1; i >= 1; i = ++i) {
cout << "Please input a number: ";
cin >> input;
total = total += input;
av_number = total / i;
cout << av_number << endl;
break;
}
} while (input >= 0);
cout << av_number << endl;
}
When I run this, the program simply adds the inputs together on each line, and then subtracts my final negative input before closing the program.
If I were to guess, It's likely a logical confliction within my sequence of do & for loops, but I'm unable to identify the issue. I may have also misused i in some fashion, but I'm not certain precisely how.
Any help would be appreciated as I'm still learning, Cheers!
you don't need the for loop, you just need some iterator to count the number of entered numbers, so you can delete that for loop and use a counter variable instead.
also, you are breaking in the loop without checking if the input < 0, so you can write this
if (input < 0)
break;
also, you shouldn't calculate av_number = total / counter; except only after the end of the big while loop
it's total += input; not total = total += input;
writing while (input >= 0) wouldn't make sense as long as you are breaking inside the loop when input < 0, so you can write while (true); instead
and this is the code edited:
#include <iostream>
using namespace std;
int main() {
float av_number = 1.0, total = 1, input = 1.0;
int counter = 0;
do {
cout << "Please input a number: ";
cin >> input;
if (input < 0)
break;
counter++;
total += input;
} while (true);
av_number = total / counter;
cout << av_number << endl;
}
and this is the output:
Please input a number: 5
Please input a number: 12
Please input a number: 7
Please input a number: -2
8
P.S : read more about Why is "using namespace std;" considered bad practice?
You should move the calculation of the average value out of the loop where the adding takes place and only add non-negative values to total.
#include <iostream>
int main() {
float total = 0.f;
int i = 0;
// loop for as long as the user successfully enters a non-negative value:
for (float input; std::cout << "Please input a number: " &&
std::cin >> input &&
!(input < 0.f); ++i)
{
// now `input` is non-negative
total += input; // and only sum it up here, no average calculation
}
if (i > 0) { // avoid division by zero
// finally calculate the average:
float av_number = total / i;
std::cout << av_number << '\n';
}
}
The condition for the loop is that std::cout << "Please input a number: " succeeds and that std::cin >> input succeeds and that input is not less than zero.

IF or WHILE for numerical input checker

I've been working on a program that calculates the mean of the user's inputs. I couldn't figure out yet, what to use for the input checker. I can't use arrays or strings yet. How do I check that both inputs are numerical values? And if they are not; how do I ask again for the correct input?
#include <iostream>
using namespace std;
int main()
{
// Get number from user
int input = 0;
double accumulator = 0;
double mean;
cout << "How many numbers would you like me to average together?\n";
cin >> input;
if (input >= 0){ //to check if input is a numerical value
// Compute and print the mean of the user input
int number = 1;
double x;
while (number <= input) //while corrected
{
cout << "Please type a numerical value now: \n";
cin >> x;
if (x < 0 || x > 0){ //to check if x is a numerical value
accumulator = accumulator + x;
}
else {
cout << "Input incorrect"<< endl;
}
number = number + 1;
}
mean = accumulator / input; // formula corrected
cout << "The mean of all the input values is: " << mean << endl;
cout << "The amount of numbers for the average calculation is: " << input << endl;
}
else {
cout << "Input incorrect"<< endl;
}
return 0;
}
You can use cin.fail to check for errors. Note that if user inputs a number followed by letters, lets say 123abc, then x will be stored as 123 but abc remains in the input buffer. You may wish to clear that right away so abc doesn't appear in the next loop.
while (number <= input) //while corrected
{
cout << "Please type a numerical value now: \n";
cin >> x;
bool error = cin.fail();
cin.clear();
cin.ignore(0xFFFF, '\n');
if (error)
{
cout << "Input incorrect" << endl;
continue;
}
accumulator = accumulator + x;
number = number + 1;
}
Alternatively you can initialize x. For example
double x = numeric_limits<double>::min();
cin >> x;
cin.clear();
cin.ignore(0xFFFF, '\n');
if (x == numeric_limits<double>::min())
{
cout << "Input incorrect" << endl;
continue;
}
If error occurs then x remains unchanged and you know there was an error, because it is unlikely that the user inputs a number matching numeric_limits<double>::min()
Not related to this issue, but you should also account for divide by zero error.
if (input == 0)
mean = 0;//avoid divide by zero, print special error message
else
mean = accumulator / input;

C++ Do-While logic is right but doesn't run correctly

The code is simple. It users Pointers to receive the input for the amount of rows and columns to be displayed in a multiplication table. I tried to have a validation system using a Do-While loop but it doesn't seem to work. Even if the values entered are outside the range it still accepts it and moves on, thus printing an incorrect table.
How can I fix this? I don't want to change the method being used too much because the way it is now is clean and simple. Is there a simple fix to this or should I just redo the logic entirely?
#include <iostream>
#include <iomanip>
using namespace std;
int passByRow(int *x);
int passByColumn(int *x);
int main()
{
int row = 0, column = 0;
int dummy;
do // Input Row
{
passByRow(&row);
} while (row >! 0 && row <! 10);
//while ((ans != 'Y') && (ans != 'N') && (ans != 'y') && (ans != 'n'));
do // Input Column
{
passByColumn(&column);
} while (column >! 0 && column <! 10);
// Display the table
cout << "\nTHE MULTIPLICATION TABLE:\n" << endl << "" << endl;
for (int c = 1; c < row+1; c++)
{
for (int i = 1; i < column+1; i++)
{
cout << i * c << '\t';
}
cout << endl;
}
cin >> dummy;
return 0;
}
int passByRow(int *x)
{
cout << "Please enter a number of rows on the interval [1, 10]: ";
cin >> *x;
return *x;
}
int passByColumn(int *x)
{
cout << "Please enter a number of columns on the interval [1, 10]: ";
cin >> *x;
return *x;
}
Instead of column >! 0 && column <! 10, try column < 1 || column > 10. Similar for row. Find some manner of documentation on C++ operators instead of guessing....

Yes or No While Loops c++

I am writing a program that allows the user to input an integer, which I then reverse and output back to them. I would like the program to run again at the user's request and allow them to enter another integer, but I'm unable to do so.
Here is what I expect my program to be able to do:
Enter a positive integer: 38475
This integer in reverse is 57483.
Would you like to do this again? (y/n) y
Enter a positive integer: 9584
This integer in reverse is 4859.
Would you like to do this again? (y/n) n
And here is my code, which currently handles reversing the input.
#include <iostream>
using namespace std;
int main()
{
int num, i = 10;
cout << "Enter a positive integer: ";
cin >> num;
cout << " This integer in reverse is ";
do
{
cout << (num%i) / (i / 10);
i *= 10;
} while ((num * 10) / i != 0);
return 0;
}
How can I have my program run multiple times based on user input?
Initialize a char to 'y'. Obtain the user input and set that to the char after the user provides the input. The while loop should look something like while (answer == 'y'). This way it'll run at least once.
As Ceelos points out in their answer you can do this with another do while loop using a single char and ask the user whether they wish to repeat the program or not. I have added an example for clarity:
int main()
{
char repeat = 'n';
do
{
int num, i = 10;
cout << "Enter a positive integer: ";
cin >> num;
cout << " This integer in reverse is ";
do
{
cout << (num%i) / (i / 10);
i *= 10;
} while ((num * 10) / i != 0);
// Ask the user if they wish to play again
cout << endl << "Would you like to have another turn?" << endl;
// Get their answer
cin >> repeat;
} while (repeat == 'y');
return 0;
}

problems with switch statement involving functions [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
This program is not prompting me for input. I need help with defining, and calling functions properly. menu() is supposed to display a string of text, and ask the user to select a number 1-4, and if the user enters a number outside of that it will ask the user to enter an appropriate number until 1-4 is entered. The value of menu() will be stored in a variable 'choice' and be used in a switch statement.
Inside of the switch statement the corresponding choice functions[getSum(), getFactor(), getExpo(), and exit()] are called. They each need to ask the user for an integer, and perform some arithmetic, and return some output text to the user with the calculated value.
All of this is inside of a do while loop repeating this process, until the user chooses the option 4 to quit the program, where the exit() function will return a string exit message to the user and then the program will terminate.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int menu();
long int getSum();
long int getFactor();
long int getExpo();
string exit();
int main()
{
const int SUM = 1, // Summation choice
FACTOR = 2, // Factorial choice
EXPO = 3, // Exponential choice
QUIT = 4; // Exit choice
int choice; // Numerical menu choice
long int sums, facts, expos;
string quits;
// Force the console to print standard notation
cout << fixed << setprecision(0);
// Do-While loop controlled by the users choices
do
{
choice = menu();
switch (choice) // Start switch option
{
case SUM: // 1st choice
sums = getSum();
break;
case FACTOR: // 2nd choice
facts = getFactor();
break;
case EXPO: // 3rd choice
expos = getExpo();
break;
case QUIT: // 4th choice
quits = exit();
break;
default: // Default choice
// Error message for input outside domain
cout << "Please make a selection of either 1,2,3 or 4.\n\n";
cin >> choice; // Repeat attempt to gather input from user
}
}
while (menu() != QUIT);
return 0;
}
int menu()
{
int choice;
cout << "\n\t\tMathematical Menu\n" // Header
<< "1) Summation\n" // 1st choice
<< "2) Factorial\n" // 2nd choice
<< "3) Exponential\n" // 3rd choice
<< "4) Exit Program\n\n" // 4th choice
<< "Please make a selection\n" // Ask user for imput choice
<< "of either 1,2,3 or 4.\n\n";
cin >> choice; // Gather input from user
return choice;
}
long int getSum()
{
int total = 0, userNum, counter;
// Ouput statement to user
cout << "Please enter a positive integer value greater than 0 \n"
<< "and less than 10,000,000.\n\n";
cin >> userNum; // Repeat attempt to gather input from user
// Compare input to domain
if (userNum < 0 || userNum > 10000000)
{
// Error message for input outside domain
cout << "Please check your entry and try again.\n\n";
cin >> userNum; // Repeat attempt to gather input from user
}
// Perform arithmetic summation
for (counter = 1; counter <= userNum; counter++)
{
total += counter; // Running count
}
cout << "The total value for the added numbers 1 to \n"
<< userNum << " is:\n"<<total;
return total;
}
long int getFactor()
{
int total, userNum, counter;
total = 1;
// Output statement to user
cout << "Please enter a positive integer from 0 \n"
<< "and less than 100.\n\n";
cin >> userNum; // Gather input from user
// Compare input to domain
if (userNum > 100 || userNum < 0)
{
// Error message if input is outside domain
cout << "Please check your entry and try again.\n\n";
cin >> userNum; // Repeat attempt to gather input from user
}
// Perform arithmetic factorial
for (counter = 1; counter <= userNum; counter++)
{
total *= counter; // Running count
}
// Display arithmetic output to user
cout << "The total value for the multiplied numbers 1 to \n"
<< userNum << " is:\n";
return total;
}
long int getExpo()
{
int total, userNum, counter;
total = 0;
// Output statement to user
cout << "Please enter a positive integer from 0 \n"
<< "and less than 100.\n\n";
cin >> userNum; // Gather input from user
// Compare input to domain
if (userNum > 100 || userNum < 0)
{
// Error message if input is outside domain
cout << "Please check your entry and try again.\n\n";
cin >> userNum; // Repeat attempt to gather input from user
}
// Perform arithmetic exponential
for (counter = 1; counter <= userNum; counter++)
{
total = pow(2.0, userNum); // Running count
}
// Display arithmetic output to user
cout << "The total value for the exponential function is \n";
return total;
}
string exit()
{
// Exit message
return "Don't be gone for too long...\n";
}`
Do not call menu() more than once: it will prompt the user twice.
Do not return anything from a function that does all the work anyway. Make it
void getExpo(){ ...; return; }
Call:
getExpo();