Re-running a Program

Hi guys, I am trying to write a program that calculates force and gives the user an option to rerun the program. The code I wrote seems to skip asking the user whether they want to rerun the program and just seems to go straight to asking the user for the input. Can anyone help me with this?




#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()

{
// initializing the variables
double mass;
double acceleration;
double force;

//asks users for mass and acceleration and stores it
std::cout <<"Please enter a number for mass (in kg). \n";
std::cin >> mass;
std::cout <<"Please enter a number for acceleration (in m/s^2) \n";
std::cin>>acceleration;

//equation to calculate force
force=mass*acceleration;

//prints out the result

std::cout<<"Here is the force for the numbers you provided. \n"<< force;

char rerun;
do {
// initializing the variables
double mass;
double acceleration;
double force;

//asks users for mass and acceleration and stores it
std::cout <<"\n Please enter a number for mass (in kg). \n";
std::cin >> mass;
std::cout <<"Please enter a number for acceleration (in m/s^2) \n";
std::cin>>acceleration;

//equation to calculate force
force=mass*acceleration;

//prints out the result

std::cout<<"Here is the force for the numbers you provided. \n"<< force<< endl;
std::cout << "\n Do you want to run this program again? (y/n) : \n";
std::cin >> rerun; }
while (rerun == 'y' || rerun == 'Y');
std::cout << "Thank you for using the force calculator." << endl;
return 0;
}
It looks like you copied the second half of the code from the first half. I took away the first half and left the part in the do while loop.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
    char rerun;

    do
    {
        // initializing the variables
        double mass;
        double acceleration;
        double force;

        //asks users for mass and acceleration and stores it
        std::cout <<"\n Please enter a number for mass (in kg): ";
        std::cin >> mass;
        std::cout <<"Please enter a number for acceleration (in m/s^2): ";
        std::cin>>acceleration;

        //equation to calculate force
        force=mass*acceleration;

        //prints out the result
        std::cout<<"Here is the force for the numbers you provided: "<< force<< endl;
        std::cout << "\n Do you want to run this program again? (y/n) : \n";
        std::cin >> rerun;
    }while (rerun == 'y' || rerun == 'Y');

    std::cout << "Thank you for using the force calculator." << endl;

    return 0;
}


This seems to work.
Last edited on
Thank you so much!
Topic archived. No new replies allowed.