[try Beta version]
Not logged in

 
Need Help With Code

Apr 2, 2008 at 5:58pm
OK, im making a simple subtraction/addidtion proggram from homework and at the beggining of the program there has to be a choice to go into a sub calculator that only adds or divides. this is what i got so far.(yes i know i write really,really, wierd. Iwas taught this way)

#include<iostream>

int main()
{
using namespace std;
float a,b,sum;
char choice1;
char choice2 = 'y';

while (choice2 == 'y')

{
cout << endl;
cout << "Calculator Program [V1.01]";
cout << endl << endl;
cout << "Choose Operation Type ";
cout << endl;
cout << "Addition=A Subtraction=s";
cout << "a or s: ";
cin >> choice1
if (choice1 == 'a')
{
cout << "Enter First Number: ";
cin >> a;
cout << "Enter Second Number: ";
cin >> b;

sum = a + b;
cout << endl;
cout << "The Sum Is " << sum;
cout << endl;

cout << endl;
cout << "Try Again? [y/n] ";
cin >> choice2;
}
else {
return 0 }
}


return 0;
}

Apr 2, 2008 at 6:26pm
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
36
37
38
39
40
41
42
43
44
#include<iostream>
using namespace std; //<-moved outside of int main

int main()
{
    float a, b, sum;
    char choice1;
    char choice2 = 'y';

    while(choice2 == 'y')
    {
          cout << endl;
          cout << "Calculator Program [V1.01]";
          cout << endl << endl;
          cout << "Choose Operation Type ";
          cout << endl;
          cout << "Addition = a Subtraction = s";
          cout << endl; //<-otherwise it was messy
          cout << "a or s: ";
          cin >> choice1; //<-added semicolon
          if (choice1 == 'a')
          {
                      cout << "Enter First Number: ";
                      cin >> a;
                      cout << endl; //<-otherwise it was messy
                      cout << "Enter Second Number: ";
                      cin >> b;

                      sum = a + b;
                      cout << endl;
                      cout << "The Sum Is " << sum;
                      cout << endl;

                      cout << endl;
                      cout << "Try Again? [y/n] ";
                      cin >> choice2;
          }
          else{
                      return 0;
          }
     }
     
     return 0;
}


Made a few small changes (where noted). Your program runs just fine so far. I suggest you change the variable of your while loop, however. As it is now, when prompted to "try again" the user can enter anything other than 'y' and it will end the loop.
Last edited on Apr 2, 2008 at 6:28pm
Apr 3, 2008 at 2:48am
That's very inefficient to say the least, but it does work.
Topic archived. No new replies allowed.