fork download
  1. //Cameron Pham CS1A Chapter 4, P. 224, #19
  2. //
  3. /*******************************************************************************
  4. *
  5. * Calculate the Speed of Sound in Gases
  6. *
  7. *______________________________________________________________________________
  8. * This program displays a menu of four gases. A gas is selected and the program
  9. * accepts a value for the time it took for sound to travel through it. The
  10. * program then calculates the distance the sound traveled.
  11. *
  12. * INPUT
  13. * Choice of gas
  14. * Time in seconds
  15. *
  16. * OUTPUT
  17. * Distance the sound traveled
  18. *
  19.  ******************************************************************************/
  20. #include <iostream>
  21. #include <limits>
  22. using namespace std;
  23. int main()
  24. {
  25. int choice; //INPUT - Menu selection for 1-4 gases
  26. float seconds; //INPUT - Time in seconds for the sound to travel
  27. float speed; //Speed of sound for the selected gas
  28. float distance; //OUTPUT - Distance sound traveled in meters
  29.  
  30. // Display the menu
  31. cout << "Speed of Sound Calculator" << endl;
  32. cout << "1. Carbon Dioxide" << endl;
  33. cout << "2. Air" << endl;
  34. cout << "3. Helium" << endl;
  35. cout << "4. Hydrogen" << endl;
  36. cout << "Enter your choice: ";
  37. cin >> choice;
  38. cout << endl;
  39.  
  40. // Validate the menu choice
  41. while (cin.fail() || choice < 1 || choice > 4)
  42. {
  43. cin.clear();
  44. cin.ignore(numeric_limits<streamsize>::max(), '\n');
  45. cout << "Invalid choice. Please enter a number 1-4: ";
  46. cin >> choice;
  47. }
  48.  
  49. // Assign speed based on menu choice using a switch statement
  50. switch (choice)
  51. {
  52. case 1:
  53. speed = 258.0;
  54. break;
  55. case 2:
  56. speed = 331.5;
  57. break;
  58. case 3:
  59. speed = 972.0;
  60. break;
  61. case 4:
  62. speed = 1270.0;
  63. break;
  64. }
  65.  
  66. // Get and validate the number of seconds
  67. cout << "Enter the number of seconds: ";
  68. cin >> seconds;
  69. cout << endl;
  70.  
  71. while (cin.fail() || seconds < 0 || seconds > 30)
  72. {
  73. cin.clear();
  74. cin.ignore(numeric_limits<streamsize>::max(), '\n');
  75. cout << "Invalid time. Please enter a value between 0 and 30 seconds: ";
  76. cin >> seconds;
  77. }
  78.  
  79. // Calculate and display the distance
  80. distance = speed * seconds;
  81. cout << "The sound source was " << distance << " meters away." << endl;
  82.  
  83. return 0;
  84. }
Success #stdin #stdout 0.01s 5320KB
stdin
4 25
stdout
Speed of Sound Calculator
1. Carbon Dioxide
2. Air
3. Helium
4. Hydrogen
Enter your choice: 
Enter the number of seconds: 
The sound source was 31750 meters away.