Hello Boogey,
A few more suggestions:
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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
|
/*Author:(My name will be here)
The following code should ask an integer number from the user.
It should then print out a menu with mathematical actions,
and asks the user to choose wich action wishes to use.
The code should repeat untill the user chooses the "e.Exit" option.
*/
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int number{}, /*i{},*/ fact = 1; // <--- ALWAYS initialize all your variables.
char e{}, menuChoice{}; // <--- "e" never used.
cout << "\n Please type a positive, non zero integer number: ";
cin >> number;
do
{
cout <<
"\n"
" a.Doubled\n"
" b.Squared\n"
" c.Square root\n"
" d.Factorial\n"
" e.Exit\n"
" Choose which action you like to use (from 'a' to 'e'): ";
cin >> menuChoice;
switch (menuChoice)
{
case 'A':
case 'a':
cout << "\n The number " << number << " doubled is: " << 2 * number << '\n';
break;
case 'B':
case 'b':
cout << "\n The number squared is: " << number * number << '\n';
break;
case 'c':
cout << "\n The number's square root is: " << sqrt(number) << '\n';
break;
case 'd':
for (int i = 1; i <= number; i++) // <--- "i" type should be defined here.
{
fact = fact * i;
}
cout << "\n The number's factorial is: " << fact << '\n';
break;
case 'e':
cout << "\n The program will now exit\n"; // <--- Changed.
menuChoice = 'e'; // <--- Make sure "menuChoice" is a lower case letter.
break;
default:
cout << "\n invalid action!\n";
}
} while (menuChoice != 'e');
return 0; // <--- Not required, but makes a good break point for testing.
}
|
The comments should explain most of it.
Unless you need "i" outside the for loop, which you do not here, define the loop iterators' type in the for loop. Keep the variable local to the loop.
Please use better variable names. It makes the code easier to follow.
Watch you indenting it helps.
When you write:
case 'a' : cout<<"The number doubled is: "<<2*x<<endl;
. That is nice and it works, but save it for the future. For now having each line of code on its own line will help in understanding the error messages that come up. If you have a line with 2 or more statements the compiler may not tell you where the error is just what line number it is in.
When I mentioned using (\n) notice in the code there are some places where you can put the (\n) at the end of the string.
The blank lines really do help with readability. Remember you are writing this code for some one to read not for the compiler.
Case 'A' and 'B' demonstrate how you can check for either case.
Line 56 makes sure that "y" is a lower case letter for the while condition. There are other ways to check for case
while (y != 'e' && y != 'E');
or change the case after input.
Andy