fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. using namespace std;
  4.  
  5.  
  6. long double getUserInput()
  7. {
  8. cout << "Please enter a number: \n";
  9. long double x;
  10. cin >> x;
  11. return x;
  12. }
  13.  
  14. char getMathematicalOperation()
  15. {
  16. cout << "Please enter which operator you want (add +, subtract -, multiply *, or divide /): \n";
  17. char o;
  18. cin >> o;
  19. return o;
  20. }
  21.  
  22. long double calculateResult(long double nX, char o, long double nY)
  23. {
  24. // note: we use the == operator to compare two values to see if they are equal
  25. // we need to use if statements here because there's no direct way to convert chOperation into the appropriate operator
  26.  
  27. if (o == '+') // if user chose addition
  28. return nX + nY; // execute this line
  29. if (o == '-') // if user chose subtraction
  30. return nX - nY; // execute this line
  31. if (o == '*') // if user chose multiplication
  32. return nX * nY; // execute this line
  33. if (o == '/') // if user chose division
  34. return nX / nY; // execute this line
  35. return -1; // default "error" value in case user passed in an invalid chOperation
  36. }
  37.  
  38. void printResult(long double x)
  39. {
  40. cout << "The answer is: " << setprecision(2) << x << "\n";
  41. }
  42.  
  43. long double calc()
  44. {
  45. // Get first number from user
  46. long double nInput1 = getUserInput();
  47.  
  48. // Get mathematical operations from user
  49. char o = getMathematicalOperation();
  50.  
  51. // Get second number from user
  52. long double nInput2 = getUserInput();
  53.  
  54. // Calculate result and store in temporary variable (for readability/debug-ability)
  55. long double nResult = calculateResult(nInput1, o, nInput2);
  56.  
  57. // Print result
  58. printResult(nResult);
  59. return 0;
  60. }
  61.  
  62.  
  63. int main()
  64. {
  65. calc();
  66. }
Success #stdin #stdout 0s 3232KB
stdin
100.1 / 1001
stdout
Please enter a number: 
Please enter which operator you want (add +, subtract -, multiply *, or divide /): 
Please enter a number: 
The answer is: 0.1